# Question
Title: How do I disable the "Flood attempts IP blocking" functionality?
Drupal blocks the IP used to access the site, when a user tries to log in many times.

How can I disable this functionality?

# Answer
What you can do is adding the following code in the settings.php file.

```
$conf['user_failed_login_ip_limit'] = PHP_INT_MAX;

```

In this way, the IP will not blocked.

user\_login\_authenticate\_validate() contains the following code.

```
  if (!empty($form_state['values']['name']) && !empty($password)) {
    // Do not allow any login from the current user's IP if the limit has been
    // reached. Default is 50 failed attempts allowed in one hour. This is
    // independent of the per-user limit to catch attempts from one IP to log
    // in to many different user accounts.  We have a reasonably high limit
    // since there may be only one apparent IP for all users at an institution.
    if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) {
      $form_state['flood_control_triggered'] = 'ip';
      return;
    }
    $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();
    if ($account) {
      if (variable_get('user_failed_login_identifier_uid_only', FALSE)) {
        // Register flood events based on the uid only, so they apply for any
        // IP address. This is the most secure option.
        $identifier = $account->uid;
      }
      else {
        // The default identifier is a combination of uid and IP address. This
        // is less secure but more resistant to denial-of-service attacks that
        // could lock out all users with public user names.
        $identifier = $account->uid . '-' . ip_address();
      }
      $form_state['flood_control_user_identifier'] = $identifier;

      // Don't allow login if the limit for this user has been reached.
      // Default is to allow 5 failed attempts every 6 hours.
      if (!flood_is_allowed('failed_login_attempt_user', variable_get('user_failed_login_user_limit', 5), variable_get('user_failed_login_user_window', 21600), $identifier)) {
        $form_state['flood_control_triggered'] = 'user';
        return;
      }
    }
    // We are not limited by flood control, so try to authenticate.
    // Set $form_state['uid'] as a flag for user_login_final_validate().
    $form_state['uid'] = user_authenticate($form_state['values']['name'], $password);
  }

```

The limits are actually two: one for the case Drupal always has an IP, and one for when Drupal has also a user ID. The latter is for the case the user enters a username for an existing account; in that case, Drupal register the user ID, and the IP.
If you want to avoid also that case, then you need to add also this line to the setting.php file.

```
$conf['user_failed_login_user_limit'] = PHP_INT_MAX;
$conf['user_failed_login_user_window'] = 5;

```
> 12 votes

# Answer
In **Drupal 8**, you can change the flood settings in the config file `user.flood.yml`.

```
uid_only: false
ip_limit: 50
ip_window: 3600
user_limit: 5
user_window: 21600
_core:
  default_config_hash: UYfMzeP1S8jKaaaavxf7nQNe8DsNS-3bc2WSNNXBQWs

```

This means that per IP and per user, there is a limit:

* Per 3600 seconds (1 hour), 50 attempts per IP address are allowed
* Per 21600 seconds (6 hours), 5 attempts per user account are allowed (quite few)

You might change and import the settings (i set it to 100 attempts per 5 minutes):

```
uid_only: false
ip_limit: 100
ip_window: 300
user_limit: 100
user_window: 300
_core:
  default_config_hash: UYfMzeP1S8jKaaaavxf7nQNe8DsNS-3bc2WSNNXBQWs

```
> 6 votes

# Answer
The Flood Control module will handle this elegantly.
> 5 votes

---
Tags: 7, users
---


# Question
Title: Views Geolocation field proximity: How to alter views field setting
I'm using a Geolocation field in views to order results by distance. The module provides a special views proximity plugin/field, which can be used in the "sort" section of the view. This plugin/field has a "proximity setting" (lat/long) to define the center point for distance calculation. I got this far in views UI and this all works.

I now need to programmatically change that center point based on a custom logic derived from the current user, but I don't know which views hook to use to alter this field setting.

Tried, didn't work:

```
function MYMODULE_views_pre_view($view, $display_id, &$args) {
  //my field's machine name is "field_geo"
  $geoField = $view->display_handler->getHandler('field', 'field_geo_proximity');
  //print_r($geofield) is empty

  //suffix "_proximity" seems to be added by geolocation module, but does not work either
  $geoFieldProximity = $view->display_handler->getHandler('field', 'field_geo_proximity');
  //print_r($geofieldProximity) is empty
}

```

I've got two questions:

1. Is `pre_view` the correct hook to alter the field setting? (If not, which hook should I use instead?)
2. How to I get/set those field settings?
I thought I need to use `$view->display_handler->getHandler()` but didn't get any results.

# Answer
Digging through the exported `views.yml` config helped me to get on the right track:

```
function MYMODULE_views_pre_view($view, $display_id, &$args) {

  if ($view->id() == 'WHATEVER' and $display_id == 'MY_DISPLAY') {
    $allFields = $view->display_handler->getOption('fields');

    $user = _MY_BUSINESS_LOGIC();
    if (!$user->get('field_geo')->isEmpty()) {
      $allFields ['field_geo_proximity']['proximity_lat'] = $user->get('field_geo')->lat;
      $allFields ['field_geo_proximity']['proximity_lng'] = $user->get('field_geo')->lng;
      $view->display_handler->overrideOption('fields', $allFields);
    }
  }
}

```
> 0 votes

---
Tags: views, 8
---


# Question
Title: Changing form field requirement via ajax
I have a selectbox field, that should change the disabled and required states of another field based on the value selected in the selectbox field. The change must be done via ajax.

In my modules form\_alter function I have the following code:

```
$form['field_type_app_details']['widget']['#ajax'] = array(
  'callback' => 'ajax_type_callback',
  'event' => 'change'
);
if ($form['field_type_app_details']['widget']["#default_value"][0] === 'First') {
  unset($form['field_version']['#disabled']);
  $form['field_version']['widget'][0]['value']['#required'] = true;
} else {
  $form['field_version']['#disabled'] = 'disabled';
  $form['field_version']['widget'][0]['value']['#required'] = false;
}

```

And the corresponding ajax\_type\_callback function looks like this:

```
function ajax_type_callback($form, $form_state) {
  return $form['field_type_app_details'];
}

```

What I would expect is, that when I change the value in the selectbox, to i.e. "Second", that the required and disabled states of field\_version change accordingly.

What actually happens is, that when I change the value in the selectbox, the ajax request fires correctly, but doesn't change anything of field\_version. Additionally, not even the changed value of field\_version is saved, when the form gets submitted.

Where is the mistake?

# Answer
Thanks to @Clive for pointing me in the right direction.

I've managed to accomplish what I want with the following changes to the form\_alter function:

```
$form['field_type_app_details']['widget']['#ajax'] = array(
  'callback' => 'ajax_type_callback',
  'event' => 'change',
  'wrapper' => 'version-release'
);
$form['field_version']['#prefix'] = '<div id="version-release">';
$form['field_version']['#suffix'] = '</div>';
$typeValueChangedByUser = $form_state->getValue(['field_type_app_details', 0, 'value']);
$typeToCheck = $typeValueChangedByUser ? $typeValueChangedByUser : $form['field_type_app_details']['widget']['#default_value'][0];
if ($typeToCheck  === 'First') {
  unset($form['field_version']['#disabled']);
  $form['field_version']['widget'][0]['value']['#required'] = true;
} else {
  $form['field_version']['#disabled'] = 'disabled';
  $form['field_version']['widget'][0]['value']['#required'] = false;
}

```

And the following change to the ajax\_callback function:

```
function ajax_type_callback($form, $form_state) {
  return $form['field_version'];
}

```
> 0 votes

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


# Question
Title: Flush cache in case of WSOD without Drush on shared host
I have installed Drupal from using build-in scripts on runcloud.io, but I have noticed that Drush is not available. They have replied:

> Sorry, it is not possible to install drush into Runcloud. Because the installation leads to php crash as it will erase cerain php modules

I get used to using Drush, especially when Drupal 8 website encountered an unexpected error, without this option I don't see the way how to clear the cache without UI, restore from backup etc.

Are there any other options to rebuild caches without Drush to recover the website from an unexpected error?

# Answer
> I get used to using Drush, especially when Drupal 8 website encountered an unexpected error, without this option I don't see the way how to clear the cache without UI.

Run `www.mysite.com/update.php`. This clears the cache, even when no updates are to run.

If you don't have access set `$settings['update_free_access'] = TRUE;` temporarily in settings.php.
> 2 votes

---
Tags: 8, drush
---


# Question
Title: Installing Drush on Mac OS 10.13 (High Sierra)
I've been struggling for a few days getting drush to install properly on my Mac.

I've followed the instructions on https://www.drupal.org/node/1674222

Composer installs fine, but when I `cd` into `drush-master` and run `composer install`, I get:

```
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for drush/drush No version set (parsed as 1.0.0) -> satisfiable by drush/drush[No version set (parsed as 1.0.0)].
    - drupal/core 8.0.0-beta9 requires phpunit/phpunit 4.4.* -> satisfiable by phpunit/phpunit[4.4.0, 4.4.1, 4.4.2, 4.4.3, 4.4.4, 4.4.5] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta8 requires phpunit/phpunit 4.4.* -> satisfiable by phpunit/phpunit[4.4.0, 4.4.1, 4.4.2, 4.4.3, 4.4.4, 4.4.5] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta7 requires phpunit/phpunit 4.4.* -> satisfiable by phpunit/phpunit[4.4.0, 4.4.1, 4.4.2, 4.4.3, 4.4.4, 4.4.5] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta6 requires phpunit/phpunit 4.4.* -> satisfiable by phpunit/phpunit[4.4.0, 4.4.1, 4.4.2, 4.4.3, 4.4.4, 4.4.5] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta15 requires phpunit/phpunit 4.6.* -> satisfiable by phpunit/phpunit[4.6.0, 4.6.1, 4.6.10, 4.6.2, 4.6.3, 4.6.4, 4.6.5, 4.6.6, 4.6.7, 4.6.8, 4.6.9] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta14 requires phpunit/phpunit 4.6.* -> satisfiable by phpunit/phpunit[4.6.0, 4.6.1, 4.6.10, 4.6.2, 4.6.3, 4.6.4, 4.6.5, 4.6.6, 4.6.7, 4.6.8, 4.6.9] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta13 requires phpunit/phpunit 4.6.* -> satisfiable by phpunit/phpunit[4.6.0, 4.6.1, 4.6.10, 4.6.2, 4.6.3, 4.6.4, 4.6.5, 4.6.6, 4.6.7, 4.6.8, 4.6.9] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta12 requires phpunit/phpunit 4.6.* -> satisfiable by phpunit/phpunit[4.6.0, 4.6.1, 4.6.10, 4.6.2, 4.6.3, 4.6.4, 4.6.5, 4.6.6, 4.6.7, 4.6.8, 4.6.9] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta11 requires phpunit/phpunit 4.6.* -> satisfiable by phpunit/phpunit[4.6.0, 4.6.1, 4.6.10, 4.6.2, 4.6.3, 4.6.4, 4.6.5, 4.6.6, 4.6.7, 4.6.8, 4.6.9] but these conflict with your requirements or minimum-stability.
    - drupal/core 8.0.0-beta10 requires phpunit/phpunit 4.4.* -> satisfiable by phpunit/phpunit[4.4.0, 4.4.1, 4.4.2, 4.4.3, 4.4.4, 4.4.5] but these conflict with your requirements or minimum-stability.
    - Installation request for webflo/drupal-core-strict 8.6.x-dev -> satisfiable by webflo/drupal-core-strict[8.6.x-dev].
    - drupal/alinks 1.0.0 requires drupal/core * -> satisfiable by drupal/core[8.0.0, 8.0.0-beta10, 8.0.0-beta11, 8.0.0-beta12, 8.0.0-beta13, 8.0.0-beta14, 8.0.0-beta15, 8.0.0-beta16, 8.0.0-beta6, 8.0.0-beta7, 8.0.0-beta8, 8.0.0-beta9, 8.0.0-rc1, 8.0.0-rc2, 8.0.0-rc3, 8.0.0-rc4, 8.0.1, 8.0.2, 8.0.3, 8.0.4, 8.0.5, 8.0.6, 8.0.x-dev, 8.1.0, 8.1.0-beta1, 8.1.0-beta2, 8.1.0-rc1, 8.1.1, 8.1.10, 8.1.2, 8.1.3, 8.1.4, 8.1.5, 8.1.6, 8.1.7, 8.1.8, 8.1.9, 8.1.x-dev, 8.2.0, 8.2.0-beta1, 8.2.0-beta2, 8.2.0-beta3, 8.2.0-rc1, 8.2.0-rc2, 8.2.1, 8.2.2, 8.2.3, 8.2.4, 8.2.5, 8.2.6, 8.2.7, 8.2.8, 8.2.x-dev, 8.3.0, 8.3.0-alpha1, 8.3.0-beta1, 8.3.0-rc1, 8.3.0-rc2, 8.3.1, 8.3.2, 8.3.3, 8.3.4, 8.3.5, 8.3.6, 8.3.7, 8.3.8, 8.3.9, 8.3.x-dev, 8.4.0, 8.4.0-alpha1, 8.4.0-beta1, 8.4.0-rc1, 8.4.0-rc2, 8.4.1, 8.4.2, 8.4.3, 8.4.4, 8.4.5, 8.4.6, 8.4.7, 8.4.8, 8.4.x-dev, 8.5.0, 8.5.0-alpha1, 8.5.0-beta1, 8.5.0-rc1, 8.5.1, 8.5.2, 8.5.3, 8.5.4, 8.5.5, 8.5.6, 8.5.7, 8.5.8, 8.5.x-dev, 8.6.0, 8.6.0-alpha1, 8.6.0-beta1, 8.6.0-beta2, 8.6.0-rc1, 8.6.1, 8.6.2, 8.6.3, 8.6.x-dev, 8.7.x-dev].

```

etc...

Can someone tell me how to do this right?

# Answer
> Drush 9 only supports one install method. It requires that your Drupal 8 site be built with Composer and Drush be listed as a dependency.

---

See http://docs.drush.org/en/master/install/

There it's recommended you start your Drupal 8 project with Composer. Then add Drush as local dependency to your project and use this local Drush to do things.

```
$ cd drupal
$ composer require drush/drush
$ vendor/bin/drush cr

```

Using the Composer template for Drupal projects Drush already is listed as a dependency.

```
$ cd ~/Sites
$ composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction
$ cd some-dir
$ cd web
$ ../vendor/bin drush si

```

Additionally you then can install the Drush Launcher which will replace the global `drush` command with a wrapper that always automatically finds and executes the local Drush in every directory.

---

If all of this is no option for you you might want to have a look at Having multiple Drush instances for different core versions where I show how you'd still be able to install a global Drush quite easily.
> 2 votes

---
Tags: drush
---


# Question
Title: Attach a simple custom handler to a Webform
I'm trying to create a custom webform handler. I'd like to be able to attach my handler to any webform and have it display the message 'xyz' when the (multi step wizard) form is finally submitted. I have this file in my custom module at: `my_module/src/Plugin/WebformHandler/PostWebformHandler.php`.

```
<?php

namespace Drupal\test_b\Plugin\WebformHandler;

use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform test b handler.
 *
 * @WebformHandler(
 *   id = "test_b",
 *   label = @Translation("Test B"),
 *   category = @Translation("Test B"),
 *   description = @Translation("Test B webform submission handler."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */
class TestBWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    \Drupal::messenger()->addMessage(t('xyz'));
  }

}

```

On navigating to my Webform settings, I see:

but when I click *Add handler* for *Test B* it does not attach to my form handlers?

# Answer
The above code works. My mistake was in the naming of things. Name all files, classes etc. *foo* and it will attach.
> 0 votes

---
Tags: webforms
---


# Question
Title: Translation: File upload error. Could not move uploaded file
I would like to import an translation file \*.po. When I import it, I become the error: "For security reasons, your upload has been renamed to bootstrap-all.de\_.po." and "Error message File upload error. Could not move uploaded file."

Could anyone help?

# Answer
> 1 votes
Try this:

* Go to `admin/config/media/file-system` page
* Set **Temporary directory** field to `sites/default/files/temp`
* Save changes

**ALSO**

* Check that `sites/files` is writable.

---
Tags: debugging
---


title: Separate grid rows by field value

text:
# Question
Title: Separate grid rows by field value
I have a custom content type with fields in which I collect, among others things, country. I'm using Drupal 8. I'd like to create a grid view page (using Views) of the content that is separated by country like shown in the image.

I'd like to avoid creating mupltiple views, one for each country, and then collating them into yet another page.

Any suggestions on how to make it happen?

# Answer
## Use Grouping by a Field

Grouping by Fields is a standard feature in Views.

1. Create your Content Views with Page Display
2. Add the Country Field (Probably a Taxonomy term reference, there are ways to import country lists BTW)
3. Set `Format` to **Grid** and set **Number of columns**
4. In `Format` `Settings` set **Grouping field Nr.1** to your Country field

Check in Preview that things look the way you want.
5. Edit the Country field and set it to **Exclude from display** because you have it output above each result group, your probably don't want it in each grid cell too
6. Edit the Country field `Style settings` if you want more control over how the "group headings" are output, but this works only in certain cases: D7 How to change the HTML wrapped around a grouping output (HTML h3 tag), D8 Allow to configure the h3 element for view style plugins, although you can use `Custom text` field for more control too.
> 1 votes

---
Tags: views
---


# Question
Title: Increase weight range for child pages in book outlines (Book module)
When a child page is added to a book via "Add child page" (node/add/{content-type}), the Weight drop-down field in the Book Outline tab has a range of -/+ 15. This is due to line 191 in web/core/modules/book/src/BookManager.php:

```
$form['book']['weight'] = [
  '#type' => 'weight',
  '#title' => $this->t('Weight'),
  '#default_value' => $node->book['weight'],
  '#delta' => max(15, abs($node->book['weight'])), // line 191
  '#weight' => 5,
  '#description' => $this->t('Pages at a given level are ordered first by weight and then by title.'),
 ];

```

When a child node is initially added, $node-\>book\['weight'\] is always 0, resulting in a #delta value of 15. #delta controls the min and max values in the Weight drop-down field mentioned above. There is no way to assign a weight higher than 15.

To simplify the work of non-technical editors repetitively adding chapters to books, we tell them to set the Weight value to the chapter number. This doesn't work for books with more than 15 chapters (which happens).

QUESTION: What is the correct, non-core-hacking way to set the limit to say, 25 in Drupal 8? (see my answer below)

AMENDMENT ADDED 2018-11-24

In addition to the issue expressed above, a related issue is that on the book outline reorder page (admin/structure/book/{book-nid}) there is a drop-down field for the weight of each child page. Child pages with a current weight within the range -/+ 15 get a range of -/+ 15 in their drop-down fields. Child pages with weights outside that range get a drop-down with the range increased to include their current weight.

This is due to lines 202, 203, and 235 in web/core/modules/book/src/Form/BookAdminEditForm.php:

```
$count = count($tree); // line 202 - count of all child pages for the book
$delta = ($count < 30) ? 15 : intval($count / 2) + 1; // line 203

$form[$id]['weight'] = [
  '#type' => 'weight',
  '#default_value' => $data['link']['weight'],
  '#delta' => max($delta, abs($data['link']['weight'])), // line 235
  '#title' => $this->t('Weight for @title', ['@title' => $data['link']['title']]),
  '#title_display' => 'invisible',
  '#attributes' => [
    'class' => ['book-weight'],
  ],
];

```

The challenge with varying the weight range based on current weight is that it's not possible to assign a weight greater than 15 to a child page whose current weight is 15 or less because its drop-down allows a maximum of 15. I can add several child pages with weight 0, but I can't change any of them to 16. Maybe I'm missing something in the current user interface?

All of this said, there seems to be a fairly straightforward solution to both of these problems, explained in my answer below. Not knowing every detail of how the Book module works, there may be flaws in what I suggest. I'm using it right now and it seems to work well, but I welcome corrections or suggestions for improvement.

# Answer
Having spent quite some time reading others' posts and in trial and error, I came to this answer to my own question (as amended above).

Create a custom module (see drupal.org/docs/8/creating-custom-modules). In the MYMODULE.module file, add the following (replace "section" with the content type you're using):

```
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
  switch($form_id) {

    case 'node_section_form':
    case 'node_section_edit_form':
    case 'node_section_book_outline_form:

      $form['book']['weight']['#delta'] = 25;
      break;

    case 'book_admin_edit':

      foreach ($form['table'] as $key => &$arr) {

        if (strpos($key, 'book-admin-') === 0) {
          $arr['weight']['#delta'] = 25;
        }
      }

      break;
  }
}

```

The first case increases the weight range on the add content page, on the edit content page, and on the book outline page for the content type. The second case increases the weight range for each child on the reorder book outline page.

This is working well for me, but I welcome corrections and suggestions for improvement, especially suggestions for making the solution less "brittle".

NOTE THAT even when you've done this, the editor will still have to clear the cache and refresh the book outline to get added child pages or reordering to show up in the redisplayed book outline.

FIRST UPDATE TO ANSWER:

Based on more reading and more trial and error, it appears that adding the following to a custom .theme file (see drupal.org/docs/8/theming) will disable caching of the book navigation block for all but anonymous users. Thus, editors who add or reorder child pages will see their changes immediately upon returning to the book outline without clearing the cache.

```
function MYTHEME_preprocess_block(&$vars)
{
  if ($vars['plugin_id'] == 'book_navigation') {
    $vars['#cache']['max-age'] = 0;
  }
}

```

SECOND UPDATE TO ANSWER:

The answer given above for overcoming the clear cache problem works, but it requires a cache clear before changes made by an editor are seen by anonymous users.

A better solution is, instead of adding the code above to the .theme file, to add this (replace "section" with the content type you're using):

```
function MYTHEME_preprocess_block(&$vars)
{
  if ($vars['plugin_id'] == 'book_navigation') {
    $vars['#cache']['tags'] = ['node_type:section'];
  }
}

```

And then add the following to the .module file (again, replace "section" with the content type you're using):

```
use Drupal\node\NodeInterface;
use Drupal\Core\Cache\Cache;

function MYMODLE_node_presave(NodeInterface $node)
{
  if ($node->getType() == 'section') {
    Cache::invalidateTags(['node_type:section']);
  }
}

function rsc_module_node_delete(NodeInterface $node)
{
  if ($node->getType() == 'section') {
    Cache::invalidateTags(['node_type:section']);
  }
}

```

This solution retains the benefit of caching the book navigation block and invalidates it only when a section in it is changed or deleted. Thus, both editors and anonymous users see the editor's changes immediately when a change is made to a section.
> 1 votes

# Answer
Many people agree it's a big accessibility problem, but it isn't easy to solve and there always seem to be some obstacle.

I just posted about this, possible duplicate, very relevant for this question because the listed issues mention various methods on how to approach solving this and the obstacles you might encounter: How to increase book weight range for a same-level chapters.

The simplest way to solve it might be to rely on an outside sorting method, like Weight, and not on overriding the Book module. I don't have enough expertise to evaluate the difficulty level to modify the Book code, it just seems that way reading the lines and between them on those threads.
> 0 votes

---
Tags: 8, nodes
---


title: How to add Google fonts locally

text:
# Question
Title: How to add Google fonts locally
At the moment, I have this in my template.php

```
drupal_add_css('https://fonts.googleapis.com/css?family=Short+Stack',array('type' => 'external'));

```

I now have the .woff is the theme's folder. What's the proper way to add it?

# Answer
> 4 votes
1. Use the google-webfonts-helper or a similar tool to download **all** possible font formats (only `*.woff` won't be enough regarding cross-browser compatibility).
2. Store the font files somewhere in your theme, maybe in a subfolder called `/fonts`.
3. Use `@font-face` in your CSS to load the fonts as described in this brilliant CSS-Tricks article: Using @font-face

---

> ```
> @font-face {
>   font-family: 'MyWebFont';
>   src: url('../fonts/webfont.eot'); /* IE9 Compat Modes */
>   src: url('../fonts/webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
>        url('../fonts/webfont.woff2') format('woff2'), /* Super Modern Browsers */
>        url('../fonts/webfont.woff') format('woff'), /* Pretty Modern Browsers */
>        url('../fonts/webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
>        url('../fonts/webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
> }
>
> body {
>   font-family: 'MyWebFont', SomeFallbackFont, sans-serif;
> }
>
> ```

---
Tags: theming
---


# Question
Title: How to make one view with different taxonomy terms in different rows?
I want to make a view with 3 rows of lets say fruits, with 6 fruits max for each row. Spring, Summer and Autumn fruits.

And I don't want them to be mixed in one array so I could style them in view-template. How can I do it correctly?

# Answer
> 1 votes
I wanted to post this as a comment but my rep is not high enough. I had asked a similar question and received an answer here: Separate grid rows by field value

---
Tags: views, theming, taxonomy-terms
---


# Question
Title: Update the author_uid for an entity registration
I'm looking to update the author\_uid for an Entity Registration in Drupal 7 programatically. I want to replace all anonymous users with the UID of 0 with another UID lets say 2 upon saving the registration. I have tried three different solutions thus far to no avail.

Solution 1) Update the author\_uid in the $form\_state prior to saving the registration form.

```
<?php
function registration_form_alterations_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == "registration_form") {
        dpm($form);
        dpm($form_state);
        $form['#submit'][] = 'registration_form_alterations_custom_submit';

    }
}

function registration_form_alterations_custom_submit($form, &$form_state) {
    //  submit handler code
    dpm($form_state);
}

```

This didn't work because author\_uid isn't available to be altered in form\_state to the best of my knowledge.

Solution 2) Update via hook\_entity\_presave. I'm not sure this will work because I can't seem to isolate the actual registration entity to update the author\_id in hook\_entity\_presave.

Solution 3) Use rules... Which doens't allow you to update the author\_uid. A rules message screen comes back with a message about the value not being writable/editable.

Does anyone have any additional thoughts on this. Sorry I know its a bit of a weird request, but we have a user that wants anonymous registrations reassigned to them so that they can manage additional details associated with the registrations.

# Answer
> 1 votes
(a) `hook_entity_presave()` should work, giving you access to the entity, before it is persisted, e.g.:

```
/**
 * Implements hook_entity_presave().
 */
function registration_alterations_entity_presave($entity, $type) {
  if ($type === 'registration' && $entity->author_uid === 0)) {
    $entity->author_uid = variable_get('registration_alterations_anonymous_registrations_reassign_uid');
  }
}

```

(b) Alternatively, you could use `hook_field_attach_submit()`, which is also triggered inside `registration_form_submit()` and would give you access to the submitted form in case you needed it. This would look similar to (a):

```
/**
 * Implements hook_field_attach_submit().
 */
function registration_alterations_field_attach_submit($entity_type, $entity, $form, &$form_state) {
  if ($entity_type === 'registration' && $entity->author_uid === 0)) {
    $entity->author_uid = variable_get('registration_alterations_anonymous_registrations_reassign_uid');
  }
}

```

Good luck!

---
Tags: 7, entities, hooks, rules
---


# Question
Title: How to increase book weight range for a same-level chapters
I have a book of 33 chapters. These chapters are numbered with roman numbers: Chapter I, chapter II and so on.I'm a blind user, so I can't use drag & drop reorder. In **Drupal 7**, weight range is -15 to 15. There is a way to modify this range? Or there is an other module similar to book module, with the same navigation style?

# Answer
I was surprised to hear that the weight range numbers are limited, I expected to get a number input field (so I could enter any number value) but instead, the weight choice widget is a select options type, and for the Book module weights it really is limited to values between -15 and 15, and it still is in Drupal 8!

This is an important accessibility issue, but it doesn't seem so easy to fix once you dig into it. This was on the radar for a long time: Reordering fails with more than 31 book pages in a book that turned to Add a scalable weight select element which circled back to Improve #weight select element behavior based on the number of items and finally in D8 Books: Better Sorting. Maybe you can test that patch and help get it implemented in D8? There is an Accessibility Group you can join and advocate for better weights handling without javascript.

In the meantime, there is a number of modules you can use to reorder book pages a different way.

Book helper seems to be the best to try out first.

There's also a comparison page: Comparison of Node/Entity Ordering Modules
> 2 votes

# Answer
I've proposed a Drupal 8 solution to the book weight range problem. The solution is likely very similar for Drupal 7. See Increase weight range for child pages in book outlines (Book module). Corrections and suggestions for improvement are solicited and welcome.
> 0 votes

---
Tags: nodes, navigation
---


# Question
Title: How to customize a link with a custom module?
I installed the "Private Message" module on Drupal 8.

There is a link to send a message that I want to transform into a Bootstrap button.

How to customize a link on Drupal 8 ?

Here is the HTML code of the link :

```
<div class="private_message_link_wrapper"><a href="/private_messages/9" class="private_message_link">Envoyer un message</a></div>

```

The developer of "Private Message" gave me this code, but I do not know what to do with it.

I need to create a custom module or put it in `my_theme.info.yml` ?

```
function HOOK_node_view_alter(&$build) {
  $build['private_message_link']['#title'] = t('Click me. Click me now!');
}

```

The developer of the module wrote in a comment :

```
You can implement hook_ENTITY_TYPE_view_alter(). For example, if you are altering the link on the user profile you would implement hook_user_view_alter(). If you are altering the link on nodes, you would implement hook_node_view_alter(). If you are altering the link on comments, you would implement hook_ENTITY_TYPE_view_alter().

In this function, you can change the output of the link by altering $build['private_message_link'] as you see fit.

```

**I created a custom module:**

`private_message_contact_button.module` :

```
<?php

/**
 * @file
 * Hook implementations of private_message_contact_button module.
 */

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

function private_message_contact_button_node_view_alter(&$build) {
  $build['private_message_link']['class'] = array('button button--primary', 'btn');
}

```

The code works, but the button is not applied.

I want to add class `btn btn-success`

And I want to add an icon make awesome in front of the text `<i class="fas fa-comment fa-lg"></i>`

I have to put what as code ?

# Answer
The CSS class is a sub-key of the `#attributes` of a render array like `$build`:

```
function private_message_contact_button_node_view_alter(&$build) {
  if (array_key_exists('private_message_link', $build)) {
    $build['private_message_link']['#attributes']['class'] = array('button button--primary', 'btn');
  }
}

```
> 1 votes

---
Tags: 8, theming, nodes, bootstrap-theme
---


# Question
Title: View conditional logic based on dropdown value
I have a `view` that is outputting fields from a `paragraph`. I want to be able to output different markup. There are two available values in the dropdown

```
1|Wrapping Link
2|Internal Link

```

and they should determine if the markup is wrapped by a link or if the same link is a contained within the markup as a stand-alone link.

In my custom version of `views-view-fields.html.twig` I want to have some logic in place that will check the value of the dropdown and display the correct markup. I have tried the following but this is invalid.

```
{%- if {{ fields.field_banner_type.content }} = "1" -%}
    // wrapping link
{%- else -%}
    // no wrapping link
{%- endif %}

```

# Answer
> 0 votes
No need to `{{ fields.field_banner_type.content }}` inside if statement use `fields.field_banner_type.content` like the following:

```
{% if fields.field_banner_type.content == "1" %}
  {# wrapping link #}
{% else %}
  {# no wrapping link #}
{% endif %}

```

For more info See Twig if Documentation

---
Tags: views
---


# Question
Title: How to include tpl inside another tpl with parameters?
I have worked with `drupal 8`, i included twig template inside another twig template file like the bellow.

```
{% include module_path ~ 'templates/template.html.twig' with {
    'content': someVars,
 }
%}

```

Now i need to do the same with Drupal 7.
Is there any way to do something similar in drupal 7 ?

# Answer
> 2 votes
I find the best way is to use hook\_theme instead of dirty requires/includes. Can make for a really nice component driven workflow.

In module or theme:

```
    /**
     * Implements hook_theme().
     */
    function mymodule_theme($existing, $type, $theme, $path) {

      $path = drupal_get_path('theme', 'my_theme') . '/templates/components';

      return array(
        'my_template'  => array(
          'template' => 'my-template',
          'path' => $path,
          'variables' => array(
            'var1' => 'hello'
          )
        ),
      );
    }

```

In your template

```
   print theme('my_template' array('var1' => 'yo'));

```

# Answer
> 0 votes
I'm not sure if this is a good practice, but you can do that in your tpl:

```
<?php
$my_content = "test";
include "archive.tpl.php";
?>

```

Then, in your archive.tpl.php you can work with $my\_content

# Answer
> 0 votes
Another option: within the outer template call "print render(theme($variables...))". It might also be possible call theme() in the preprocess function.

---
Tags: 7, theming
---


# Question
Title: Cannot add a file with Search API Attachments
I'm using Search API with Solr and Tika under D8 to build a search engine on my website.

I could not find any tutorial under D8 for that, so I followed one I've found on D7. However, when I try to add a field "file" to my index, it appears in a section called "Skipped fields" with the following message :

> The following fields cannot be indexed since there is no type mapping for them:
>
> Source » File (type "entity:file")
>
> If you think one of these fields should be available for indexing, please report this in the module's issue queue. (Make sure to first search for an existing issue for this field.) Please note that entity-valued fields generally can be indexed by either indexing their parent reference field, or their child entity ID field.

Has anyone managed to index files using Search API Attachments ? I cannot understand how to fix this message.

Also, it does not make sense to me to "index their parent reference field" because this will put an ID in Solr, and not a real text file metadata ..

# Answer
> 0 votes
there are some steps to follow in the module README.txt file :

https://cgit.drupalcode.org/search\_api\_attachments/tree/README.txt?h=8.x-1.x#n81

---
Tags: 8, search
---


# Question
Title: Programmatically create a comment form for a node
I'm trying to port a theme from Drupal 6 to Drupal 8, and I find code like the following.

```
$edit = array();
$edit['nid'] = $node->nid;
$form = drupal_get_form('comment_form', $edit));

```

How do I load the form in Drupal 8? I get the following error:

> Fatal error: Call to a member function getEntityTypeId() on null in /www/site/core/lib/Drupal/Core/Entity/EntityForm.php on line 77

The line causing the error is the following one:

```
\Drupal::formBuilder()->getForm('Drupal\comment\CommentForm');

```

I can't work out how to pass the node object to the form builder. How can I do it?

# Answer
`FormBuilder::getForm()` doesn't accept just a single argument; it accepts additional arguments that are passed to the functions called by `FormBuilder::getForm()`, including the unique form constructor function. These values are available to implementations of `hook_form_alter()` and `hook_form_FORM_ID_alter()` as `$form_state->getBuildInfo()['args']`.

To build an entity form, though, Drupal core uses the entity.form\_builder service instead of form\_builder. The following is the code used in `CommentLazyBuilders::renderForm()` to build the comment form.

```
$values = [
  'entity_type' => $commented_entity_type_id,
  'entity_id' => $commented_entity_id,
  'field_name' => $field_name,
  'comment_type' => $comment_type_id,
  'pid' => NULL,
];
$comment = $this->entityTypeManager->getStorage('comment')
  ->create($values);

return $this->entityFormBuilder->getForm($comment);

```

`EntityFormBuilder::getForm()` accepts two arguments more; the second one is the operation to be done on the entity. Passing `'delete'` as second argument, the code would obtain the form to delete the entity.
> 2 votes

# Answer
kiamlaluno's solution didn't work for me. This did:

```
$values = array(
    'entity_type'  => 'node',
    'entity_id'    => $node->id(),
    'field_name'   => 'comment',
    'comment_type' => 'comment',
    'pid' => NULL,
);

$comment = \Drupal::entityTypeManager()->getStorage('comment')->create($values);
$formHTML  = \Drupal::service('entity.form_builder')->getForm($comment);

```
> 2 votes

# Answer
Example in core using lazy builder approach to make it work properly with caching per permission

http://cgit.drupalcode.org/drupal/tree/core/modules/comment/src/Plugin/Field/FieldFormatter/CommentDefaultFormatter.php#n194
> 1 votes

---
Tags: forms, 8
---


# Question
Title: How to move Composer created folder of drupal-8.x.x up one level to html?
So I created a fresh install of Ubuntu 16.04 and installed the LAMP stack, installed phpmyadmin and composer and then finally drush. Everything worked fine until I downloaded and installed Drupal using the "drush pm download" command which worked fine but now my entire drupal site is located in a folder called "drupal-8.6.3". I used to use the wget command and the tar --strip components command to get it properly organized.

I can delete the drupal-8.6.3 directory but how can I download my drupal site using composer or drush from the html folder?

# Answer
Since you are using `composer` to manage dependencies, you should install Drupal with Composer instead of using `drush pm-download`:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#download-core

Also, you should use Composer to manage contributed modules instead of using `drush pm-install`:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#managing-contributed

You can even use Composer to manage third-party libraries:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#third-party-libraries

And to apply patches to Drupal core and contrib modules:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#patches

Don't worry, you'll still use `drush` for a lot of things -- but once you've switched to using Composer to manage dependencies, you should stick with it as much as possible and avoid using Drush makefiles or installing / upgrading with Drush.

Here's an article with some common "gotchas" you may encounter when managing Drupal with Composer:

https://www.jeffgeerling.com/blog/2017/composer-and-drupal-are-still-strange-bedfellows
> 1 votes

---
Tags: drush, composer
---


# Question
Title: Can Display Suite be used for "Show: Fields" as well as "Show: Content" to be able to rewrite field output?
I need to be able to adjust field output in view results but also want to make use of Display Suite for layout.

However, it would appear that Display Suite is only available for "Show: Content" and not "Show: Fields" View Display Format and therefore the facility to rewrite output is not available.

Definition and comparison of "Show: Content" vs "Show: Fields"

In Views, what is the difference between "Show Fields" and "Show Content" under Format?

# Answer
> 1 votes
The answer is: no. But there is an alternative solution.

No - (At the time of writing), Display Suite does not *appear* to have functionality for laying out fields in a view result row for “Show: Fields” format.

For laying out views row results, using display suite is only available for Views outputting the full node (i.e. Show: Content) as a row. The layout is done in the manage display section of the content type, defining a view mode for use in outputting the node in the view.

The solution therefore for laying out fields ( “Show: Fields” format ) and so making available the standard view functionality to modify each field's output behaviour for the view row result would be:

---
Tags: views, 8, display-suite
---


# Question
Title: How to set webform message below the submit button?
I need to render the HTML of the errors messages below the submit button for styling purpose. I find out about Inline Form Errors; however, this will display an error message after the field and not after the submit button.

Any idea how can achieve this?

# Answer
> 1 votes
Try form alter method you can add text like following:

```
 $form['some_text'] = array(
      '#markup' => '<p>Some text</p>'
    );

```

Hope it will help!!

# Answer
> 0 votes
Webform is essentially a node. **$message variable** is rendered in **page.tpl.php** and it outputs all messages (errors, status, warnings). If you don't have anything else on the page but your form, and you don't mind outputting all kinds of messages that may appear on the page under your submit button, then - overriding page template for that one form might work.

You would create a page--node--nodeID.tpl.php. Move $message variable below $content variable. Clear cache. This is a quick but not a very elegant approach.

# Answer
> 0 votes
There is other good way : You can check for the errors in the form and set error message to the submit button. See below code -

```
$errormsg = form_get_errors();
if (isset($errormsg['test_list'])) {
  $form['botcont']['submit']['#suffix'] = '<div class="messages error messages-inline">' . $errormsg['test_list'] . "</div>";
}else {
  $form['botcont']['submit']['#suffix'] = NULL;
}

```

---
Tags: 7, webforms
---


# Question
Title: Unable to access Views fields in block Twig template
How Drupal 8 uses Twig, how different data is transferred from general template to specific templates?

For view block I have created block template as per default template suggestions. In my new Twig template if I print `{{ content }}` everything (view result fields) are getting rendered as per Drupal default.

How can I access and apply my theme markup to all view fields in my block template. `{{ dump(_context|keys) }}` display below.

# Answer
In **block--views-block--page-fields-block-1.html.twig**

You can access the view fields like this:

```
{% for row in content['#view'].result %}

  {{ content['#view'].field['field_name'].value(row) }}
  // change field_name to the actual field machine name.

{% endfor %}

```

---

Personally, I rather use **views-view-fields--\[view-name\]--\[machine-name\].html.twig**

In your case should be views-view-fields--page-fields--block-1.html.twig

Here you do not need to do a `for` loop and you can access the fields easily with:

```
{{ fields.field_name.content }}
// change field_name to the actual field machine name.

```
> 10 votes

# Answer
If you want to render the block into your custom template:

1. Create your twig file `block--views-block-page-fields-block-1.html.twig` inside `templates` folder in your custom module.
2. implement `hook_theme` like the following:

```

    /**
     * Implements hook_theme().
     */
    function yourModuleName_theme($existing, $type, $theme, $path) {
      return [
        'block__views_block_page_fields_block-1'     => [
          'base hook' => 'block'
        ],
      ];
    }

```
3. Clear cache.
4. Now you have `content` variable.

If you use Twig Tweak you can use `drupal_view_result` to get view result, so you can access to the fields like:

```
{% for result in drupal_view_result(content['#view'].id, content['#view'].current_display) %}
  {{ result._entity.field_name.value }}
{% endfor %}

```
> 1 votes

---
Tags: views, theming, blocks
---


# Question
Title: Conditional clauses with Entity field Query
I have a syntax issue on using conditional clauses with EFQ, but the documentation on drupal.org is a bit unclear for me. I have google the whole Internet for this with no results at all. My hook implementation is based on another drupal.stackexchange question

The code works for a single -\>fieldCondition but when I try to implement the hook below,

```
    $query = new EntityFieldQuery();
    $entityFormSubmissionIds = $query->entityCondition('entity_type', 'entityform')
      ->addTag('or')
      ->execute();

```

> /\** Implements hook\_query\_TAG\_alter
>
> @param QueryAlterableInterface $query \*/

```
function mymodule_query_or_alter(QueryAlterableInterface $query) {
 $or = db_or()->condition('field_a',$term->tid)
       ->condition('field_B', $term->tid);
    ->condition($or)
    ->execute();

```

Fatal error: Call to undefined method DatabaseCondition::execute()

# Answer
In the alter hook, you should not be calling execute(). You don't want to run the query at this point, just change it.

```
function mymodule_query_or_alter(QueryAlterableInterface $query) {
 $or = db_or()->condition('field_a',$term->tid)
       ->condition('field_B', $term->tid);
 $query->condition($or)
}

```
> 0 votes

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


# Question
Title: views exposed filter to have dropdown of entity reference in cutstom entity
I generated with drupal console utility my own module and content entity code. After I added a user entity reference field and a taxonomy term entity reference field.

Now I'm listing my content with views, I don't do nothing with the code generated the integration is done.

But, when I expose a filter by taxonomy field and user field it doesn't give me the option to show as a dropdown, it directly appears as a textfield.

In others views, listing nodes with entity reference fields, if I add exposed filter of entity reference offers to me a dropdown or autocomplete widget.

What I have to change to my entity to have dropdown select for my entity reference field as exposed filter in a view?

Here is the field definition in the Entity class

```
    $fields['term_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Log type'))
  ->setDescription(t('The term ID of the Log entry type.'))
  ->setRevisionable(FALSE)
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default:taxonomy_term')
  ->setSetting('handler_settings',
    array(
      'target_bundles' => array(
        'logs_type' => 'logs_type'
    )))
  ->setTranslatable(FALSE)
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'taxonomy_term',
    'weight' => -2,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => -2,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

Update:

I achieve to have a dropdown in the exposed filter in my view creating the file mymodule.views.inc and puting this code:

```
function log_activity_views_data_alter(&$data) {
  $data['log']['term_log_tid_depth'] = array(
    'help' => t('Display content if it has the selected taxonomy terms, or children of the selected terms. Due to additional complexity, this has fewer options than the versions without depth.'),
    'real field' => 'term_id',
    'argument' => array(
      'title' => t('Log type (with depth)'),
      'id' => 'taxonomy_index_tid_depth',
      'accept depth modifier' => TRUE,
    ),
    'filter' => array(
      'title' => t('Has taxonomy terms (with depth)'),
      'id' => 'taxonomy_index_tid_depth',
    ),
  );
}

```

But when I choose a term to filter the view, it does not return any item and it should do so.

# Answer
As Berdir said, as long as https://www.drupal.org/node/2429699 is not ready, you need to provide your own Views Filter plugin.

I created this plugin, based on TaxonomyIndexTid, for Nodes, see https://gist.github.com/StryKaizer/ae1cb9abc4844a9e7ac12317a9d84a78

You need to place this file in a custom module at yourmodule/src/Plugin/views/filter/NodeIndexNid.php, and also implement hook\_views\_data\_alter in your yourmodule.module file, like this:

```
/**
 * Implements hook_field_views_data_alter().
 *
 * Views integration for entity reference fields which reference nodes.
 * Adds a term relationship to the default field data.
 *
 * @see views_field_default_views_data()
 */
function yourmodule_field_views_data_alter(array &$data, FieldStorageConfigInterface $field_storage) {
  if ($field_storage->getType() == 'entity_reference' && $field_storage->getSetting('target_type') == 'node') {
    foreach ($data as $table_name => $table_data) {
      foreach ($table_data as $field_name => $field_data) {
        if (isset($field_data['filter']) && $field_name != 'delta') {
          $data[$table_name][$field_name]['filter']['id'] = 'node_index_nid';
        }
      }
    }
  }
}

```
> 4 votes

# Answer
Views currently only offers that for taxonomy\_term references, as taxonomy.module provides a special Views integration.

There are core issues open to make this generic, for example: https://www.drupal.org/node/2429699.

Until that is resolved, you have to provide your own Views Filter plugin for this, based on \Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTid, and add a views\_data handler to your entity type where you override the used filter for that field, like taxonomy.module does for all entity reference fields pointing to terms in taxonomy\_field\_views\_data\_alter()
> 1 votes

# Answer
The module Entity Reference Exposed Filters offers the possibility to generate a Views exposed filter of the referenced Titles entities.
> 1 votes

---
Tags: views, 8, entities, console
---


title: current_timestamp in date field

text:
# Question
Title: current_timestamp in date field
How can I add current\_timestamp or now for date feild in drupal database schema.

```
        'created' => array(
            'description' => t('Timestamp when the fee schedule was added.'),
            'type' => 'int',
            'not null' => TRUE,
            'unsigned' => TRUE,
        ),

```

# Answer
> 7 votes
You can specify a driver-specific column type for MySQL using the `mysql_type` attribute:

```
function MYMODULE_schema (){
  $schema['table_name'] = array(
    'fields' => array(
      'created' => array(
        'mysql_type' => 'timestamp',
        'not null' => TRUE
      )
    )
  );

  return $schema;
}

```

Then, on enabling your module, you can simply modify the column to add the default/on-update behaviour:

```
function MYMODULE_enable() {
  db_query('
    ALTER TABLE {table_name}
    MODIFY created TIMESTAMP NOT NULL
    DEFAULT CURRENT_TIMESTAMP
    ON UPDATE CURRENT_TIMESTAMP'
  );
}

```

I've just tested that on Drupal 7 and it works a treat.

**NOTE:** If you don't want the timestamp to update every time the record is updated then just remove the `ON UPDATE CURRENT_TIMESTAMP` part of the query.

# Answer
> 1 votes
I assume you are referring to MySQL, the feature you want to look into straight from the docs is time stamps.

This would probably update the db table created by schema to the field type you are looking for:

```
MODIFY COLUMN `created` TIMESTAMP NOT NULL DEFAULT current_timestamp;

```

Just stumbled on this post stating timestamp support should be in for Drupal 8, so I assume (and I coud be wrong) it probably is not supported out of the box for D7. Just change the type to TIMESTAMP in your array, and see what gives but I would not wager on this working through the D7 schema api.

**UPDATE:**

Actually, look in the post. The patch will add support to timestamp in D7. Major kudos to drupalshrek for sharing this with us.

Database schema, once patched would be as follow:

```
<?php
$schema['vchess_moves'] = array(
  'description' => 'Contains the list of moves for each game',
  'fields' => array(
    'timestamp' => array(
    'description' => 'Exact date and time of the move',
    'type' => 'timestamp',
    'not null' => TRUE,
?>

```

Go see the post above for the patch, I won't repost his stuff here, not sure if doing so would be proper.

Hope this helps, happy coding.

# Answer
> 0 votes
Here is the solution for Drupal 8.6.x just incase if someone is looking as I was :)

```
'created' => [
  'mysql_type' => 'timestamp',
  'not null' => TRUE,
  'mysql_default' => CURRENT_TIMESTAMP,
 ],

```

this is equivalent to ...

```
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

```

---
Tags: database
---


title: States with a variable

text:
# Question
Title: States with a variable
I have to do a form and in this form I have a select to choose a value, from this value I load a node and from this node I get a boolean.

With this boolean I have to show or not another form field, but I don't find the way to do this.

First I try to add an `#access` to the field I need to show or not, and the access value is defined by this : `$access = ($is_liberte ? TRUE : FALSE);`

And here is the form element :

```
$form['info_voyage']['order_id'] = array(
  '#title' => t('Order ID'),
  '#type' => 'select',
  '#access' => $access
);

```

And to reload this I try to add a callback on the first field with this function :

```
function _ga_facture_date_callback($form, $form_state){
  return $form['info_voyage']["product_id"];
}

```

This function reload the form (I think), when I change the field with the callback the function is called and the form is recalculated, so my access value change in the form field but the field doesn't appear.

What am I doing wrong?

I also think to do a states on the field to show but I have searched and I doesn't find any way to do a form states with a variable, and not another field.

# Answer
Presuming that the node IDs for the primary select are known or can be retrieved dynamically following some conditions, you can use the following pattern to display and populate the secondary select conditionally.

```
/**
 * Implements hook_form().
 */
function form_example_form($form, &$form_state) {

  $options = [];

  $nodes = node_load_multiple([
    '70',
    '71',
    '72',
    '73',
    '74',
    '75',
  ]);

  foreach ($nodes as $product) {
    $options[$product->nid] = $product->title;
  }

  $form['node_select'] = [
    '#type'    => 'select',
    '#title'   => t('Select a node'),
    '#options' => $options,
    '#ajax'    => [
      'callback' => '_secondary_select_ajax_callback',
      'wrapper'  => 'foo-bar',
    ],
  ];

  // You need a wrapper to provide a HTML ID to be targeted by the callback.
  $form['secondary_select_wrapper'] = [
    '#type'       => 'container',
    '#attributes' => ['id' => 'foo-bar'],
  ];

  // The secondary select is hidden initially.
  $form['secondary_select_wrapper']['secondary_select'] = [
    '#type'    => 'select',
    '#title'   => t('Select a value'),
    '#options' => [],
    '#access'  => FALSE,
  ];

  $form['submit_button'] = [
    '#type'  => 'submit',
    '#value' => t('Click Here!'),
  ];

  return $form;
}

/**
 * Secondary Select AJAX Callback.
 */
function _secondary_select_ajax_callback(&$form, &$form_state) {

  $options = [];
  $nid = $form_state['values']['node_select'];
  $node = node_load($nid);

  // Do whatever you need to do to populate your options.
  // ...

  $form['secondary_select_wrapper']['secondary_select']['#access'] = TRUE;
  $form['secondary_select_wrapper']['secondary_select']['#options'] = $options;

  return $form['secondary_select_wrapper'];
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to validate allowed file types in custom module
I want to validate a field with accepted file type as PDF, XLS, JPEG, JPG, GIF, ZIP, RAR and PNG.

I'm getting file types as PDF, XLS etc. here is part of my code.

```
if ($fi_name!='') {

  if ($p_filefilename[1] != 'pdf'
    ||$p_filefilename[1] != 'xls'
    ||$p_filefilename[1] != 'jpeg'
    ||$p_filefilename[1] != 'jpg'
    ||$p_filefilename[1] != 'zip'
    ||$p_filefilename[1] != 'rar'
    ||$p_filefilename[1] != 'png') {

    $form_state->setErrorByName('document', $this->t('Please upload document  in pdf, xls, jpeg, jpg, gif, zip, rar and png file.'));
  }
}

```

Even when I'm uploading PDF files it's going to error part and showing my message as "Please upload document in pdf, xls, jpeg, jpg, gif, zip, rar and png file."

What am I doing wrong?

# Answer
> 1 votes
That's basic logic. Change your ORs to ANDs.

```
if ($p_filefilename[1] != 'pdf'
  && $p_filefilename[1] != 'xls'
  && $p_filefilename[1] != 'jpeg'
  && $p_filefilename[1] != 'jpg'
  && $p_filefilename[1] != 'zip'
  && $p_filefilename[1] != 'rar'
  && $p_filefilename[1] != 'png') {

  $form_state->setErrorByName('document', $this->t('Please upload document  in pdf, xls, jpeg, jpg, gif, zip, rar and png file.'));
}

```

Anyway, you should use `in_array()` for that check. For example:

```
$allowed_types = array('pdf','xls','jpeg','jpg', 'zip','rar','png');
if (!in_array($p_filefilename[1], $allowed_types) {
  // ...
}

```

---
Tags: 8, forms, files
---


# Question
Title: How to make a view with dynamic Items to Display?
I have a website that has a give away of tickets for shows. Some times I have 2 tickets to give, sometimes 20... So I wanted to know how to dynamically change the "items to display" accordingly to somewhere else but not that static number that I put when I create the view. Because when I do the shuffle, it displays EVERYBODY that submitted and I have to manually count according to the num. of tickets I got. It can be a programmatically change or a module.

edit: I wasn't very clear, I didn't express myself well. Ppl go to my website and submit to giveaways of tickets. I just want to show a list of winners for the tickets according to the numbers of tickets I have, so it displays only the winners. Right now, it displays everybody that submitted (after a shuffle because the list is in alphabetic order) for the giveaway because I can't change the "Items to display", so when people go see who won, the page show a giant list. I cant create a view for every giveaway cause I have plenty per week and it would be so much work. Basically what I want: 3 tickets -\> a list with 3 items(winners), 4 tickets -\> a list with 4 items(winners). Sorry for those who tried to answer, I'm new to all this stack overflow thing.

# Answer
> 1 votes
Just disable paging and do "show all items". This will show all results without a pager. As for other results being mixed in (shuffle?) that can be solved by adding better filters or contextual argument filters to modify the query to just the tickets you want to show.

---
Tags: views
---


title: save/get data from map field type

text:
# Question
Title: save/get data from map field type
What I want to do is give a possibility to the user to save as many images as he likes. For this, I have created a specific field type

```
    $fields['photo_ids'] = BaseFieldDefinition::create('map')
  ->setLabel(t('Photos'))
  ->setDescription(t('The photo ids of the Item entity.'))
  ->setSettings([
    'max_length' => 50,
    'text_processing' => 0,
  ])
  ->setDefaultValue('');

```

here I want to save, add, delete IDs of pictures. Not sure if this is the best approach to this problem. The problem is I can't find the way in Drupal 8 to serialize/deserialize and save these data into the database;

# Answer
You should not create your content type programmatically, if there's no special reason. Take a look at any intro like this https://www.youtube.com/watch?v=Nfu6nckjuno \- then create a content type and fields with the excellent admin UI.

Serialization to DB is done by the Drupal core.
> 2 votes

---
Tags: 8
---


# Question
Title: How to programmatically get the NID of the current node
I've pored over this old thread on drupal.org and it just kind of makes my head spin around. Pulling down the path and trying to parse out the NID from within it? There has to be a better way.

And solutions like

```
global $node;
$nid = $node->nid;

```

don't work in my custom module (though I'm told they work in templates?). No error or anything, it just instantiates `$node` with a `NULL` value.

It feels like there must be something really obvious that I'm missing.

So, how do you get the NID of the current node without a template, while following best practices and building a reasonably robust module?

# Answer
> 56 votes
Assuming your code is running for a node page, the methods I see used most often in core/contrib modules are either using `menu_get_object()` or `arg()`:

```
if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
}

```

or

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

```

I personally prefer the first method (even though assignment in condition isn't considered a good idea by some people), but both are perfectly valid.

# Answer
> 5 votes
Easiest way to do this in Drupal 8 since arg() no longer works:

```
$path_args = explode('/', current_path());
print $path_args[1];

```

Change record

# Answer
> 4 votes
`arg(0)` returns 'node' and `arg(1)` returns node nid.

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
}

```

# Answer
> 3 votes
In D8:

```
$node = \Drupal::routeMatch()->getParameter('node');

```

# Answer
> 1 votes
The second method in the currently accepted answer is the cleanest in D7. The first answer:

```
if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
}

```

is only visually cleaner. In fact, `menu_get_object()` is calling quite a lot of code and may lead to unforeseen errors. I was using it inside a `hook_node_grants()` function and ran into a PHP Fatal error:

> Maximum function nesting level of '256' reached, aborting!

The explanation, found at https://drupal.stackexchange.com/a/69232/9158

> The infinite loop you are noticing is caused from the fact that `menu_get_object()` causes Drupal to verify the currently logged-in user has access to the node, which causes your implementation of `hook_node_grants()` to be invoked again, which calls `menu_get_object()`, which causes your implementation of `hook_node_grants()` to be invoked again, which...

This was solved by using the second method:

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

```

# Answer
> -1 votes
Another option, in D7:

```
function _my_module_get_nid() {
  $path_args = explode('/', current_path());
  //$nid = $path_args[1];
  if(is_int($path_args)) {
    return($path_args[1]);
  }
  // Log that we failed to load a NID.
  else {
    watchdog('my_module', 'Unable to gather NID at: ' . current_path(),  WATCHDOG_WARNING, NULL);
  return FALSE;
  }
}

```

If you plan to use the function outside your module, do not use the leading _ at the begining of the name of the function.

# Answer
> -1 votes
```
<?php
if (isset($node->nid) && count($node->nid) > 0){
  $mynodeid = $node->nid;
}
?>

```

---
Tags: nodes
---


# Question
Title: How to hide label in customized contact form?
I added a field 'Contact\_Catégorie (system name: field\_contact\_categorie)' to the default 'feedback' contact form.

The field type is List (Text) in which I store a set of "email address | label" in order to redirect the email to the proper recipient depending on the item selected in the list. That works well!

My issue is about the form display: whatever I choose for the label (Above, On the same line, Hidden, not displayed), the label (Contact\_Catégorie) appears in the form.

Any idea?

# Answer
The Display settings are for the message that is sent. Setting label visibility in this section would impact how it appears in the email body.

The Manage Form Display are the settings for the form - unfortunately there are no options for label display. You can alter the form by implementing hook\_form\_alter() https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Form!form.api.php/function/hook\_form\_alter/8.2.x OR if you just want to hide that label you could do it with CSS in your theme, a simple `display: none;` should work.
> 0 votes

# Answer
There's no way to do this using backend at the moment. I found this issue but it doesn't appears to be active. If you are using a custom theme, you can template the field or use some custom CSS to hide the label from display.
> 0 votes

---
Tags: 8, emails
---


# Question
Title: Different attribute selection widget in a view
I have a product display that lists multiple products with various pack sizes. I added a taxonomy field to a Product for the attribute e.g. T shirt 1 pack T shirt 3 pack

I have set the product display to list the pack sizes as a radio list for selection. Easy enough, in Configure Taxonomy Field I just set the "Enable this field to function as an attribute field on Add to Cart forms." and set the attribute selection widget to Radio buttons.

I would also like to show all the product displays in a view, also easy however, I would like the add to cart form in the view to display the pack sizes as a Select list.

T Shirt \> dropdown 1 & 3 pack Trousers \> dropdown 1 & 3 pack

Any suggestions how I can achieve this?

# Answer
> 0 votes
Since the field definition isn't context sensitive (i.e. it can't have one value on a standalone page and another on a View for that setting), you're going to have to do this yourself via a form alter. Just be mindful that the options array for radio buttons / select lists are treated differently with respect to sanitization when formatted for display.

---
Tags: commerce
---


# Question
Title: How to cancel an order transition if failure is detected in Commerce 2 / State Machine
I'm trying to plug into order transitions in order to send my order to a custom fulfillment system.

I have a transition called "send\_to\_fulfillment", and order states "reviewing" and "sent\_to\_fulfillment".

I'm hooking into the commerce\_order.send\_to\_fulfillment.pre\_transition event. What I can't figure out is how to cancel the transition if the process fails. I can certainly just throw an exception and let the site die, but I'd prefer to be able to elegantly stop the transition and inform the user of the error.

Any tips? I've tried WorkflowTransitionEvent::stopPropagation which didn't do it, and I can't seem to find it documented anywhere.

# Answer
We don't have a "cancel" or "reverse" feature right now, but it would be worth a feature request in the State Machine queue. The main thing you / we'll need to overcome is what to do in the event a transition in progress has already saved data, triggered 3rd party services, etc. Presumably, there are certain things that should *prevent* a transition from being reversed (e.g. I've refunded a payment card and therefore *must* move the order to a canceled or at least unpaid state). However, other things may fall somewhere in the middle ... be allowable and not prevent reversal.

Lisa had a great idea, too, in that you could define the reverse transition explicitly yourself and trigger it in the event that you had a failure condition in your active transition. That would allow you to encode your own logic for checking / reversing transition side effects.
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: Add a view with a contextual filter not on a node/taxonomy page
Druapl 7 - I have a taxonomy vocabulary called ‘Destinations’ and an entity created called “accommodation”. The accommodation entity contains names of individual accommodations, to simplify, let’s use hotels. So:

**Entity type: accommodation**

* Hotel X - San Diego
* Hotel Y - Barcelona
* Hotel Z - Rome

What I want to do is create pages that show which accommodation is available in which city. So I need to create a page for each:

/san-diego/accommodation /barcelona/accommodation /rome/accommodation

I can do this by adding a custom page:

/admin/structure/pages/add

I have created a view but can’t quite get my head around how to use contextual filters and relationship to show only the hotels available at each accommodation page.

How will Drupal “know” that this page should show hotels in San Diego:

/san-diego/accommodation

I understand contextual filters and relationships and use them all the time, but can’t figure out how to do this in the case.

What is the best way to create these pages and add the view?

# Answer
You already have Views that list all the content tagged with a Taxonomy term. The Views is called `Taxonomy term`, but it is a Content type Views listing nodes that have been tagged with a particular term.

You can Clone the Taxonomy term view and edit the clone to adjust it to your specific needs for Accomodation. Keep the original `Taxonomy term` View disabled if you don't need it. But you can keep it enabled along with the cloned instance too.

You want to change the Path to `accommodation/%`, the first part shouldn't be variable.

Also add a new Filter `Content: Type` and choose Accommodation only.

You can also change to use Fields instead of Content for more control over what is shown in each Accommodation result.

With this setting you will get pages that take term ID as the argument. If your `San Diego` term has ID `12`, then if you visit the page `/accommodation/12` you will see Accommodation nodes tagged with San Diego.

You don't have to create those pages in any other place than Views, they're already working when you type the correct path with term ID into your browser location bar.

If you want to list all the available terms you can use the Summary in the `When the filter value is NOT in the URL` option of the Contextual filter. This way when users visit the `/accommodation` path they see a list of locations. When they click on a location they see accommodation nodes associated with it.

You can use the `Menu` option to add the page to a menu of your choice.

## Use term names instead of IDs

To get the term name to appear in the path instead of the TID you have to add the Relationship to the term, and use a Contextual filter `Term name` that uses that Relationship. (Remove old Contextual `Has term ID`.)

I've covered details in another Question: How to setup view to filter based on second URL parameter?

Be careful about the Case settings, use dashes ;)

With this configuration your path will be `/accommodation/san-diego`.
> 0 votes

---
Tags: views, entities
---


title: How can I override the sort variable?

text:
# Question
Title: How can I override the sort variable?
For my view in Drupal 8 I have added a sorting criteria based on the custom field. Now, when I sort the content in the url one can see a sorting value as a name of that field.

Like ?sort\_by=field\_custom\_value

How can I override the value of the sort criteria, so that the path doesn't look so ugly.

Expected: ?sort\_by=something\_different

# Answer
This module might help Query Parameters To URL.

There's a D8 sandbox: Drupal 8 port

The module seems very useful, maybe it would get more attention if more people used it.
> 1 votes

# Answer
Change the machine name of the custom field. If you haven't used the field for much yet, that is a quick solution.

If you already have a lot of nodes with data in that field, create a new field with a nicer machine name and copy the data from the old field to the new field. There are a variety of ways to do this, but you might want to try Views Bulk Operations or Feeds Tamper.
> 0 votes

---
Tags: views, 8
---


# Question
Title: Programatically assigning multiple user role ?
I am trying to assign multiple role while creating a user programatically. I am successfully creating a user and assigning one role using below code

```
$user = \Drupal\user\Entity\User::create();
// Mandatory.
$user->setPassword('111');
$user->enforceIsNew();
$user->setEmail('abcd@gmail.com');
$user->setUsername('abcd');
$user->addRole('lecturer');
$user->save();

```

I want to assign two roles during this code execution and tried the below code but it did not work

```
$user->addRole(['lecturer','program coodinator']);

```

How do I assign this?

# Answer
If you look at User::addRole it says

> `User::addRole($rid)`
>
> **string $rid**: The role ID to add.

Therefore, this cannot be an array. Thus, you must do this separate

```
$user->addRole('lecturer');
$user->addRole('program coodinator');
$user->save();

```

If you look at class User, there is no such thing as "addRoles" or any method that allows multiple way of doing it with an array.
> 3 votes

# Answer
If you are sure the roles you are adding aren't already added to the user account, you can use the following code.

```
$roles = $user->getRoles(TRUE);
$user->set('roles', $roles + ['lecturer','program coodinator'])->save();

```

Since you are creating a user account, this code is probably sufficient. The more generic code would be the following one.

```
$roles = $user->getRoles(TRUE);
$user->set('roles', array_unique($roles + ['lecturer','program coodinator']))->save();

```

That code is similar to the code used by `User::addRole()`, with the exception it doesn't check the role being added is the *anonymous user* or the *authenticated* role.
> 1 votes

---
Tags: users
---


# Question
Title: cant loop through array with ajax_command_html
im beginner in drupal and i would like to ask why is this not looping , it just gives me first result

```
$string = $form_state['values']['search_block_form'];

  $query=db_select('node','n');
$query->join('field_data_body','b' , 'n.nid = b.entity_id');

$query
->fields('n',array('nid', 'title'))
->fields('b', array('entity_id', 'body_value'));

  $db_or = db_or();
  $db_or->condition('n.title', '%' . db_like($string) . '%', 'LIKE');
  $db_or->condition('b.body_value', '%' . db_like($string) . '%', 'LIKE');
  $query->condition($db_or);

  $result = $query->execute();

while ($row = $result->fetchAssoc()) {
      $node_title = $row['title'];
      $node_id = $row['nid'];
      $entity_id = $row['entity_id'];
      $body_text = $row['body_value'];

  $commands[] = ajax_command_html("#block-system-main", "<h1> $node_title </h1> <p> $body_text </p>"  );
  return array('#type' => 'ajax', '#commands' => $commands);

}

```

I want replace div with id block-system-main with found content

# Answer
Try with this:

```
  $string = $form_state['values']['search_block_form'];

  $query = db_select('node', 'n');
  $query->join('field_data_body', 'b', 'n.nid = b.entity_id');

  $query
    ->fields('n', array('nid', 'title'))
    ->fields('b', array('entity_id', 'body_value'));

  $db_or = db_or();
  $db_or->condition('n.title', '%' . db_like($string) . '%', 'LIKE');
  $db_or->condition('b.body_value', '%' . db_like($string) . '%', 'LIKE');
  $query->condition($db_or);

  $results = $query
    ->execute()
    ->fetchAll(PDO::FETCH_ASSOC);

  $commands = [];

  foreach ($results as $result) {
    $node_title = $result['title'];
    $node_id = $result['nid'];
    $entity_id = $result['entity_id'];
    $body_text = $result['body_value'];
    $commands[] = ajax_command_html("#block-system-main", "<h1>" . $node_title . "</h1> <p>" . $body_text . "</p>");
  }
  return array('#type' => 'ajax', '#commands' => $commands);

```
> 0 votes

---
Tags: ajax
---


# Question
Title: For external data, should I create custom table or new entity type?
I have a database that exists outside of Drupal. I wish to show the summarized data from that database on Drupal.

At a high level, you can see the structure of the data below.

```
| Seller's ID | Product Category | Date      | Total Sales |
| 1           | Widgets          | 5/1/2018  | 20000       |
| 2           | Widgets          | 5/1/2018  | 40000       |
| 3           | Widgets          | 5/1/2018  | 50000       |

```

In the past, I simply have made a custom table in Drupal and then performed SQL queries on that table using a custom module.

Within this table, I likely have hundreds of thousands of rows. As far as I can tell, I have two viable options:

1. **Entity Type** \- Create an entity type with fields that mirrors the columns that I expressed above.

* **Potential benefits:**
    I should be able to use the full power of views to create different reports. I could also make new reports from data without having to touch the custom module.
    * **Potential Disadvantages**:
    I have concerns about site performance. On a prior site, I had hundreds of thousands of nodes and it seemed like it substantially slowed down the site.
2. **Custom Table:**

* **Potential Benefits**:
    1) This would be easy to implement on the front end
    2) I would not be adding lots of nodes that MIGHT negatively affect performance.
    * **Weaknesses:**
    1) I won't be able to use the data without leveraging a custom module to query the SQL.
    2) Only developers with knowledge of creating custom modules would be able to create new representations of data.

Overall, I would prefer to create an entity type to hold the data so I can deal with the data in the front end of Drupal. With that said, I don't want to set myself up for disaster in terms of performance down the road.

Should I be worried about the database having hundreds of thousands of entities in the entity table?

Are there other options I am not aware of?

# Answer
It's really up to HOW you are going to use it. Just listing it? Will you extend it with new fields? How likely will be problem be more complex in the future?

Custom entity is a definitely good thing: it's not just about views, but lot more (entity hooks/events for example). Don't worry about performance yet, since you didn't mention anything that could be dangerous. Still regarding simplicity the table solution would be still a winner.
> 1 votes

---
Tags: entities, database
---


# Question
Title: How do I create a block only for the user "owning" the profile page?
I made so the logged in user have a recap of their last comments/added node on their profile with a view.
As I am making the profile page public, I need to be able to hide those blocks from others authenticated users.

How can I make the block visible to the user for which the profile page is?

# Answer
> 0 votes
So I found out :

* Either you can directly go in view and add a "FILTER CRITERIA" \> "(author) User: Current" and it will hide the content for user that are not the current logged in user
* Or you can go in the block settings, select "Pages on which this PHP code returns TRUE (experts only)" and add in the box `<?php global $user;
return $user->uid == arg(1); ?>` and the block disappear totally if you are not the current user.

---
Tags: views, users, blocks
---


# Question
Title: Image style not generated for specific content type in amazon s3
I have store images/files in amazon s3 using **s3fs module** when I upload images/files it stores in default public files on s3 server like **s3fs-public** folder . But I want to store images/files on specific **image styles** which I have created in back-end for specific content type . But images/files not store in specific **image styles**. So, can anyone tell me how to solved this issue.

# Answer
> 3 votes
Style - instances of images are not generated at upload. They are generated "on the fly" when requested for the first time.

---
Tags: 7, media
---


# Question
Title: Change Product type's referenced Variation type
Once a Product type is created, I cannot change Variation type in Product type. Is this a feature, or is there a way to change it?

Is it safe if I change it in the database?

This is useful because I want to use entity\_clone and create multiple similar Product types and change the variation type after the clone.

# Answer
It's safe as long as you don't have any products. We need to change the logic in Commerce so that it checks for existence of product entities, instead of just checking whether the product type is new. Continued in your issue: https://www.drupal.org/project/commerce/issues/3014686
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: How to keep the size of the database reduced?
I found out a very simple D7 site with less than 150 nodes had database dumps of 65M (gzipped). Which caused my entire server to become slow during the nightly database dumps.

After some searching I found this useful query:

```
SELECT TABLE_NAME, table_rows, data_length, index_length,
round(((data_length + index_length) / 1024 / 1024),2) "Size in MB"
FROM information_schema.TABLES WHERE table_schema = "DRUPAL_DATABASENAME_GOES_HERE";

```

With that I immediately found the culprit: the `sessions` table.

After a `TRUNCATE sessions` my dump is now \<1M (gzipped).

How can I make sure this site's dump doesn't blow up again in the future? I found periodic purging of watchdog and sessions tables? on drupal.org, but it's from 2007.

# Answer
> 3 votes
Try the modules

The differences are also explained in the this fixed issue Compare with DB Maintenance in the **Optimize Database** issue tracker.

The first can also run cron (so, optimize at midnight).

# Answer
> 5 votes
Don't dump `session`, `cache_*`, `watchdog` table **content** (make sure to keep the structure).

For watchdog there's syslog replacement.

If you don't need the access logging in Drupal disable that module and dump that table as well.

For huge content driven websites with lots of edits (and revisions) clearing the revision tables from time to time might help too. (e.g. with node revision delete).

# Answer
> 2 votes
If you find you have too many rows in the sessions table, you can adjust your PHP session settings in settings.php

```
/**
 * Set session lifetime (in seconds), i.e. the time from the user's last visit
 * to the active session may be deleted by the session garbage collector. When
 * a session is deleted, authenticated users are logged out, and the contents
 * of the user's $_SESSION variable is discarded.
 */
ini_set('session.gc_maxlifetime', 200000);

/**
 * Set session cookie lifetime (in seconds), i.e. the time from the session is
 * created to the cookie expires, i.e. when the browser is expected to discard
 * the cookie. The value 0 means "until the browser is closed".
 */
ini_set('session.cookie_lifetime', 2000000);

```

For example, you could reduce `session.gc_maxlifetime` and `session.cookie_lifetime` to purge the sessions table more frequently.

More info on session configuration:

PHP: Runtime Configuration: Session

Although not directly related to the large sessions table, using an alternative cache handler, such as Memcache can help reduce DB size by moving cache tables into Memcache instead.

# Answer
> 1 votes
Apart from some of the tables mentioned in some other answers already, there are plenty of other tables in Drupal 7 that you can either clear (to reduce the database size) or safely exclude when performing backups. Such as various search\*-, devel\*-, ctools\*- or flood tables.

For a pretty long list (inventory) of those tables, have a look at my answer to "Which tables are safe to clear?"

# Answer
> 0 votes
Try redis

This will allow you to completely remove the cache tables and speed up the site in the process

---
Tags: 7, database, sessions
---


# Question
Title: Cache max-age doesn't correctly expire at midnight
I've got a node which cache should expire every day at midnight. Additionally I've a block showing the same node in another display mode, that also should expire every day at midnight. I thought this would be pretty easy by calculating max-age

**page\_cache is already disabled** \- dynamic\_page\_cache is enabled

.module file

```
function wt_lunch_preprocess_node(array &$variables) {
  $node = $variables['node'];
  if ($node->bundle() == 'wt_lunch') {
    $maxAge = strtotime('tomorrow') - strtotime('now');
    $variables['#cache']['max-age'] = $maxAge;
    $today = strtolower(date('l'));
    $variables['max_age'] = $maxAge; // this line is just for debugging
  }
}

```

src/Plugin/Block/MyBlock.php

```
...
  public function build() {
    $maxAge = strtotime('tomorrow') - strtotime('now');
    $emptyResult = [
      '#markup' => '',
      '#cache' => ['max-age' => $maxAge]
    ];

    $node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['type' => 'wt_lunch']);

    if (!$node = reset($node)) {
      return $emptyResult;
    }

    $build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'special');
    $build['#cache']['max-age'] = $maxAge;
    $build['#attached']['library'][] = 'wt_lunch/daily';
    $build['#attached']['drupalSettings']['wt']['lunch']['timer'] = $node->get('field_lunch_daily_timer')->value;
    $build['#attached']['drupalSettings']['wt']['lunch']['from'] = $node->get('field_lunch_daily_from')->value;
    $build['#attached']['drupalSettings']['wt']['lunch']['until'] = $node->get('field_lunch_daily_until')->value;
    $build['#attributes']['class'][] = 'lunch--daily';
    return $build;
  }
...

```

This works almost every day. Almost. Every 10-15 days the cache does not expire properly and keeps rendering the block from yesterday.

Today the block didn't expire correctly again. I've previously added hidden debug comments in my Twig template, showing cache infos in the rendered HTML:

`{{ date().timestamp }}` ==\> `1543194778` (roundabout 1am yesterday)
`{{ max_age }}` ==\> `78422` (see $maxAge in code above, about 23 hours)

So I can verify that `$build['#cache']['max-age']` definitly was correctly calculated, yet I did get the outdated block today at 11am.

Can anybody give me a clue why the `max-age` of the block *sometimes* does not work?

# Answer
I believe your flaw is that if there is day where no one views a node of bundle wt\_lunch your nodes max age will get out of alignment; thus, your block will also be displaying an outdated node.

For this, don't use preprocess\_node, use Job Scheduler or hook\_cron instead.

You might also want to utilize the above with Ultimate Cron.
> 1 votes

---
Tags: 8, caching
---


# Question
Title: After calling drupal_flush_all_caches, menu items with access callback TRUE are giving access denied error
I was building a custom module that affected the front page and I found myself having to go clear the caches for it to take effect. So as part of the code, I put in `drupal_flush_all_caches()`.

After I ran the page, my website had all sorts of issues. It seems like any menu item with `'access callback' => TRUE`, is getting access denied errors for any user. These items were working fine before the cache clearing.

Current versions (yes I know I need to upgrade)

```
Drupal: 6.38
PHP version: 5.6.38
Server: Red Hat Enterprise Linux Server 7.5 x86_64

```

PHP ini values:

```
session.cookie_httponly Off
session.use_only_cookies    On
session.cookie_secure   Off
session.hash_function   0
session.cookie_domain   .example.com

```

Things I have done:

* Checked users table for uid of 0 - exists with status of 1, has role of `anonymous user`, has permission of `access content`
* Repaired database tables
* Clear browser cache
* Clear drupal cache (/devel/cache/clear)
* Rebuild menu (/devel/menu/reset)
* Clear db sessions table

Please let me know if you need additional information. Thank you.

# Answer
> 0 votes
The answer lies in some custom code I wrote to understand why some unrelated things were issuing an error. I discovered it was this when I was copying the code to my test site and then putting in this new code which resulted in the same issue on the test site. So that is how I was able to narrow it down. Going forward, I am going to have 3 sites, one for new development, one that mirrors the live site, and the actual live site. The issue comes from being in the middle of upgrading modules on the test site and so I couldn't really use it reliably to test new code, so I would code it on the live site (a big NO-NO and I really shouldn't have done this). The only reason I didn't my custom code was an issue was because I hadn't cleared the cache in a while, so the menu items were still available.

Maybe this will help someone in there processes to not be dumb like I was.

---
Tags: users, navigation, caching
---


title: Print a specific field

text:
# Question
Title: Print a specific field
I am working on my template and have gotten it laid out almost how I want.

I have it print the content with {{ page.content }} but what I need is on another part of the page I want to print out a specific field from that same content.

I tried different combinations of twig tags but none worked for me.

```
{{ page.content.field_name }}
{{ content.field_name }}
{{ item.field_name }}
{{ field_name }}
and a few others

```

I tried googling but I didn't find anything.

# Answer
> 6 votes
Consult this, you will see there is a variable `node` that is fully loaded `node` object. so try the following. one of them should work

```
{{ node.field_name.value }}
{{ node.field_name }}
{{ content.field_name }}

```

# Answer
> 6 votes
If you use Twig Tweak you can just use `{{ node.field_name|view }}` for anything (taxonomy terms, paragraphs, etc.) and it will render consistently based on whatever field display settings you have for a given field.

See the bottom item of the Twig Tweak Cheat Sheet for an example (and lots of other super-helpful stuff you can do with Twig Tweak).

---
Tags: theming, 8
---


title: Templates as content

text:
# Question
Title: Templates as content
I currently have a project with the requirement to edit templates for content like content, i.e. we will have a template content type which will be used as template for another content type.

I've looked for projects and best practices on the matter but didn't find anything. Does someone have experiences with a similar setup?

Should I use Twig and inline\_template or should I write my own template system with tokens? Other ideas?

Any help is greatly appreciated!

# Answer
> 1 votes
It sounds like what the client really wants is something like the Paragraphs module:

https://www.drupal.org/project/paragraphs

It's a good solution for creating flexible, yet structured, content.

Take a look at this video for a good idea of the promises (and pitfalls) of this approach:

https://www.oomphinc.com/notes/2018/11/component-based-design-system-drupal-8-paragraphs/

---
Tags: 8, theming
---


title: How to render a block in a template?

text:
# Question
Title: How to render a block in a template?
I installed the module "Shariff Social Media Buttons" for "Drupal 8" :

```
https://www.drupal.org/project/shariff

```

This module once installed, add a block in :

```
/admin/structure/block

```

I want to display this block in a template :

https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak

I tried with the following code :

```
{{ drupal_entity('block', shariffsharebuttons) }}

```

But the block does not work (it is not rendered on my page)

```
drush ev 'print_r(\Drupal::configFactory()->listAll("block.block."));'

```

# Answer
> 4 votes
you can use Twig Tweak Module, will gives you twig extension called `drupal_block`and you can render your block like the following :

```
{{ drupal_block('shariff_block') }}

```

Take a look to the module Cheat sheet for more info.

**Note :** Shariff Module provide block with the id `shariff_block` not `shariffsharebuttons`.

---
Tags: 8, theming, blocks
---


# Question
Title: Based on user's country filter content of same country?
Please find my problem statement here:

> Show all contents of Type "Test" belongings to that country to corresponding user of that country

My Approach:

1. Created a taxonomy term of country, Mapped this taxonomy in content type "Test" and also Mapped taxonomy to users account setting fields.
2. Trying to create view that can filter based on logged in user's country(user can belongs to more than one country) to the content's country field.

Trying with Contextual filter, but not figuring out, exactly what i need to give. Please anyone can help me in achieving this?

Or suggest me any other Better Approach

# Answer
> 1 votes
What you're missing is the bridge between users and content, and that comes through Relationships (connecting different tables from the database).

You can do this by approaching from either the content end, or the user end (Content Views or User Views type). Since the goal is to list content, I think it makes more sense to start from the content end, unless you need some more user handling that would be easier from the user then.

1. Create a Views showing your Content (Page or a Block, which ever suits you best)
2. Add a Relationship **Taxonomy term referenced from field\_country** (you probably have a different field name), you can require it since you only want nodes in the list that don't have Country empty
3. Add another Relationship **User using field\_user\_country** (you probably have a different field name), it will use the above Relationship by default. You can require it since you need users who also have the Country field not empty.
4. Add a Contextual filter **ID** from `User` Category and it will use the second Relationship by default. Configure it:
`When the filter value is NOT available`
**Provide default value**
**User ID from logged in user**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**User ID**
**Single ID**
**Hide view**
5. Adjust any other Views settings relevant to you and Save the View
6. If you've created a Block and need to place it in a Region in your theme, don't forget to adjust the Contextual Views options on the Block configure page.

---
Tags: views, 8
---


# Question
Title: D6 -> D8 : Migrate only taxonomy terms from a specific vocabulary
When doing a D6-\>8 migration, my taxonomy term migration template imports all the taxonomy terms found in the source D6 site into my specified D8 taxonomy.

How do I filter only the terms that belong to a specific vocabulary? For a D7 migration all I needed was:-

```
source:
  plugin: d7_taxonomy_term
  bundle: tags

```

Bundles are not part of D6 so is there a way to do this in the yml file? Like ...

```
source:
  plugin: d6_taxonomy_term
  ???

```

# Answer
> 0 votes
You could create a plugin, where you can use sql to query what you need.

For example:

```
<?php

namespace Drupal\custom_migration\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;

/**
 * Minimalistic example for a SqlBase source plugin.
 *
 * @MigrateSource(
 *   id = "custom_vocab_plugin",
 *   source_module = "custom_module",
 * )
 */
class CustomVocabulary extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('vocabulary', 'v')
      ->fields('v', [
        [....] // YOUR SQL HERE
      ]);
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    return [
      [....]

    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['vid']['type'] = 'integer';
    return $ids;
  }

}

```

Then you just need to use that plugin in your D6 migration:

```
source:
  plugin: custom_vocab_plugin

```

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


# Question
Title: How to Put a Comma in the Number Element of Webform?
how can I put a comma in a number element in drupal 8 webform to show in a view? For example, amounts like 1,000.00. Thanks.

# Answer
This is a known issue:

https://www.drupal.org/project/webform/issues/2290029

The problem is not actually with Drupal or Webform, it's a limitation of the HTML5 number field.
> 1 votes

---
Tags: webforms
---