# Question
Title: Allow access to user information without giving access to view user profile page
The main concern is: Nobody (anonymous/authenticated) has the permission to see the profile of any registered user on the site, so I have UNCHECKED the **View user information** permission for all roles.

On my site, I have the below roles:

* Role A
* Role B
* Administrator (Default)

I have a content type (Task) with many fields in addition to an "Entity reference" field (**field\_task\_manager**) referencing all the users on the site excluding "administrator" role.

I have created a view page display accessed only by "**Role A**" which will display some field in addition to the user id **(UID**) of the (**field\_task\_manager**)... so:

* Create a view of **page** display and **table** format of **fields**.
* Filter the view to show: content type (Task)
* add all required fields.
* add the **field\_task\_manager** field to the view
    + under the field settings, change the formatter to **Entity ID**

If logged in as super user (user:1), all seems good for me!

But if I logged in as a user of Role A and try to access the above view, I cannot see the **User ID** of the (**field\_task\_manager**).

but if I go ahead and **CHECK** again the **View user information** permission for all **Role A**, I can see now the User ID of the (field\_task\_manager).

However, with the **View user information** permission **CHECKED** for **Role A**, Now **Role A** can access any user account by simply going to: **/user/uid** and this what I don't want to happen.

**REMEMBER** The main concern is: Nobody (anonymous/authenticated) has the permission to see the profile of any registered user on the site.

How can I give the **Role A** a back end access to **user information** such as name, email, uid... but without giving him the ability to actually SEE the user profile page of any user ?

Or maybe I am doing something wrong here!

**UPDATE #1**

any user has the permission to see his own profile only and not the profiles of others as well.

There is indeed a user profile for every registered user and very well configured and on that profile there is some private fields such as **phone number**, **ID security code\*** and many other... so I need only the user owner to see his own profile without have the access to see the others user profiles.

I cannot just remove the pathes of the user profiles because I need them to have every user to access his/her own profile.

Thank you,

# Answer
You should probably look into Field Permissions and Profile (it was called Profile2 in D7) to try to create the exact structure you need.

You need to keep the `View user information` **on** for `Role
A` so they can see the necessary information on Views. Then control what is visible on the account/profile pages for particular roles.

For editing own account you might not even need the View, you only need the Edit page where users can both view/edit their info.

You can adjust which fields are visible on the View page, you can hide all if these pages aren't important in your project.

To create more control where you can view own fields but not other users' you need to set some custom field permissions.

A separate Profile page next to your Account page usually makes sense when you have a lot of user information related to the site topic, and then the usual registration login info is held in the Account as a separate page. Profile page has independent permissions so you can use that to organize your data according to access you want to achieve.

These are all different ways you can solve your problem. The exact method depends on your particular needs/project details. Look into all these options and decide which one is best suited for you.

There are, of course, even more ways how to handle this, but these are probably the most accessible and don't require custom code.
> 1 votes

# Answer
I ran into similar problem :

* I wanted to be able to expose user informations in a custom view, for wich I was obliged to check the "See user acount information" permission ;
* But I didn't want my basics roles to see other user profile page (/user/{user}), wich in fact is triggered by the latter permission.

Sadly, Drupal does not have the granularity in its permissions "See own user account informations".

I solved this conflict by creating a custom route access check. See the doc :

It is a bit tidious at first glance, but quite simple in fact. After a little try and test, I succeeded like this :

Create a module, then create in your module src/Routing/RouteSubscriber.php

```
<?php

namespace Drupal\your_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Define custom access for '/user/{user}'
    if ($route = $collection->get('entity.user.canonical')) {
      $route->setRequirement('_custom_access', '\Drupal\your_module\Access\YourCustomAccessCheck::access');
    }
  }

}

```

Secondly, create at the root of your module your\_module.services.yml

```
#File your_module.services.yml

services:
  # custom route access check for users to profile page user/{user}
  your_module.custom_route_subscriber:
    class: Drupal\your_module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

At last, create src/Access/YourCustomAccessCheck.php

```
<?php

namespace Drupal\your_module\Access;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;

/**
 * Checks access for displaying configuration translation page.
 */
class YourCustomAccessCheck implements AccessInterface{

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account, $user) {

    // Check if admin has "Administer users" permission.
    return AccessResult::allowedIfHasPermission($account, 'administer users')
      // Check if current user id = visited user id.
      ->orIf(AccessResult::allowedIf($user == $account->id()));
  }

}

```

Rebuild cache, and enjoy.

I must note that I used an EventSubscriber in my services.yml and not an AccessCheck as pointed in Drupal doc (see *Adding custom access checks on dynamic routes* in https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones), but I could not make it work with access\_check. Maybe someone can clarify here why...

It's a lightweight solution, and I think, better than using a heavy module with plenty of functionality you do not need.

Hope it helps !
> 3 votes

# Answer
The easiest way to go since you have mentioned business rules module:

1. Create a rule: Entity is viewed
2. Create a Variable Data Comparison to check if `[current-user:url:path]` equal to `[user:url:path]`
3. If Yes, DO NOTHING
4. If No, Create a Page redirect action to the home page.

Hope it will help,
> 0 votes

---
Tags: 8, users
---


# Question
Title: Triggering an action after user resets password?
I was hoping there was hook\_user\_pass\_reset, but I seem to be out of luck. Some background:

* I made a new field on users called "email\_confirmed"
* This field gets set = 1 when the user has confirmed their email address
* I don't use the "blocked" value, or the normal Drupal way, because I want users to still log in and do stuff. I only want to limit certain actions, which will only become possible after email\_confirmed = 1

So all I want to do is update this field = 1, the moment the user uses the confirmation link to change their password. So it will not be good enough to this when the user changes his password. It needs to happen the moment the user has executed the confirmation link?

# Answer
```
/**
 * Implements hook_ENTITY_TYPE_update().
 */
function MODULE_user_update(Drupal\user\UserInterface $user) {
  if (!empty($user->original)) { // check previous value exists
    if($user->original->pass->value != $user->pass->value) { // check if pass changed
      $user->field_email_confirmed->value = 1; // set new value
    }
  }
}

```
> 0 votes

# Answer
The Logintobbogan module for Drupal 7 does something similar. It implements `hook_form_alter()` for the user password reset form, which is also used for processing the one-time login link sent in the confirmation email, to set `$account->logintoboggan_email_validated` to `TRUE`.

In Drupal 8, it could be still possible to implement something similar. The difference is that the *user.reset.login* route (whose path is /user/reset/{uid}/{timestamp}/{hash}/login) is handled by a controller. Instead of `hook_form_alter()`, a module should alter the *user.reset.login* route to use a different controller, which sets the desired account field.
Alternatively, the email sent for the email confirmation could contain a link to a different route that sets the account field.
> 0 votes

---
Tags: 8, users
---


title: Will temporary file get deleted?

text:
# Question
Title: Will temporary file get deleted?
On /admin/config/media/file-system, there is the *Delete temporary files after X hours* setting.

Does this specifically refer to files in /tmp or in the temporary folder? Does t possibly delete "unused" files?

I ask because I use `file_save_data()` to save files and I'm worried that Drupal decides to delete some of these files, as they won't be referenced anywhere except in my own custom table.

# Answer
Files uploaded to managed files will be set as temporary. You need to set the file status as permanent, and add a usage, to prevent the file from being deleted.

Setting files as permanent can be done using File::setPermanent(). File usages can be added as follows:

```
$fid = 1; // The file ID
$file = \Drupal\file\Entity\File::load($fid);
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'mymodule', $entity_type, $entity_id);

```

This will add a 'usage' for the file. When deleted, you need to remove the file usage. Files that have been set to permanent, and have a file usage applied, will not be deleted.
> 2 votes

---
Tags: 8, files
---


title: Date vs Timestamp field-type

text:
# Question
Title: Date vs Timestamp field-type
My new project involves the requirement of manually setting a time of creation of nodes because they're looking into manually migrating parts of their old website into their new one. The date will mainly be used to sort the nodes, only 2 out of 6 content types will have the date printed in the frontend.

In D8 you can select between a date and timestamp field. Both output options seem to be the same. The only difference I noticed is the HTML output.

The timestamp output looks like this

```
<div class="field__item">Mon, 03/18/2019 - 18:00</div>

```

Date output looks like that

```
<time datetime="2019-03-18T18:00:17Z" class="datetime">Mon, 03/18/2019 - 18:00</time>

```

I found a documentation page for D7 on the matter: https://www.drupal.org/node/1455576 but I have the feeling that this information doesn't apply for those two field types in D8.

Which one should I choose for this purpose? And what's the difference in D8 between those two field types?

# Answer
In Drupal 8, timestamps (and created and updated) are stored as integers in the database. They do not use the native datatype. Timestamps can be added via the UI, but created and updated can only be used as basefields.

Datetime and daterange fields are stored as ISO strings: date-only as Y-m-d and date+time as the full ISO8601 format (currently without the UTC offset). These are store as plain strings, not as a native type, since the date/time handling in the default database backends is not portable.

The reason you are seeing different HTML, is that the two field types use different formatters. Your timestamp is using `TimestampFormatter` and it looks like your datetime is using `DatetimeDefaultFormatter`. It is possible to get both fields to output the same if you use the `DatetimePlainFormatter`formatter. You can also write your own formatter for timestamps to output HTML5 time. For various reasons, they formatters between the two types are different.
> 6 votes

# Answer
From a Drupal perspective, timestamp has issues with Views Filters.

In a recent D7 project, I went with timestamp just to keep things consistent since I was doing custom module date field queries.

In D7 I noticed that View filters only works if you enter a timestamp rather than a date, this is silly! Which makes me think most people use date, since it did not a have this filter issue. I got around this issue by utilizing views query alter and converting the date string to timestamp.

D8 might also have this issue. So perhaps the safest, most traveled, road is to use date.
> 3 votes

---
Tags: 8, datetime
---


# Question
Title: Drupal 7 how to use item menu as MENU_LOCAL_TASK and MENU_NORMAL_ITEM simultaneous?
I have hook\_menu with 3 pages they are defined by default as MENU\_NORMAL\_ITEMs and I see them from in main menu:

```
$items['accounting'] = [
    'title' => 'Accounting',
    'page callback' => 'accounting_extras_unprocessed_page',
    'access arguments' => ['access accounting extras'],
    'file' => 'accounting.pages.inc',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'weight' => 10,
  ];

  $items['accounting/extras'] = [
    'title'   => 'Extras',
    'page callback' => 'accounting_extras_unprocessed_page',
    'access arguments' => ['access accounting extras'],
    'file' => 'accounting.pages.inc',
    'weight'  => 0,
    'menu_name' => 'main-menu',
  ];

  $items['accounting/report'] = [
    'title'            => 'Report',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['accounting_report_form', 'report'],
    'access arguments' => ['access accounting report'],
    'file'             => 'forms/accounting_report.inc',
    'weight'           => 1,
    'menu_name'        => 'main-menu',
  ];

  $items['accounting/transfer'] = [
    'title'            => 'Internal transactions',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['accounting_report_form', 'transfer'],
    'access arguments' => ['access accounting report'],
    'file'             => 'forms/accounting_report.inc',
    'weight'           => 2,
    'menu_name'        => 'main-menu',
  ];

```

But I also need to see them as MENU\_LOCAL\_TASK and if I add `type = MENU_LOCAL_TASK` then they disappear from menu and appear as local tasks

What to do to see them in both places? Thank you.

# Answer
You can use a bitwise operator for that, e.g.

```
MENU_LOCAL_TASK | MENU_NORMAL_ITEM

```

There's a real-world example in the core comment module (`comment_menu()`):

```
$items['admin/content/comment'] = array(
  'title' => 'Comments',
  'description' => 'List and edit site comments and the comment approval queue.',
  'page callback' => 'comment_admin',
  'access arguments' => array('administer comments'),
  'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
  'file' => 'comment.admin.inc',
);

```
> 1 votes

---
Tags: 7, navigation
---


# Question
Title: Can't Write to Public Files but Permissions Appear Fine
Need the internet to confirm my sanity. On a Drupal 7 site it's saying "The directory sites/default/files is not writable." So I checked every permission but I don't see the issue. Since this isn't a public server, I temporarily turned off SELinux. Another Drupal 8 site is running on the same server with the exact same permissions. What am I missing?

`getenforce` output:

```
Permissive

```

`ps aux | grep httpd` output:

```
root     29064  0.0  0.1 262224  6492 ?        Ss   18:26   0:00 /usr/sbin/httpd -DFOREGROUND
apache   29065  0.0  0.0 261884  3672 ?        S    18:26   0:00 /usr/sbin/httpd -DFOREGROUND
apache   29066  0.0  0.2 1188648 10040 ?       Sl   18:26   0:00 /usr/sbin/httpd -DFOREGROUND
apache   29067  0.0  0.2 1778408 8000 ?        Sl   18:26   0:00 /usr/sbin/httpd -DFOREGROUND

```

`/sites/default/files` is a symlink and the permission should be ignored

```
lrwxrwxrwx 1 root   root    31 Mar 18 18:14 files -> /mnt/efs/website/publicfiles/

```

So let's go down the tree

```
drwxr-xr-x 12 root root 6144 Feb 17 23:27 efs

```

```
drwxr-xr-x 4 root root 6144 Feb 17 23:28 website

```

```
drwxrwxr-x 110 apache web 141312 Mar 18 18:16 publicfiles

```

EDIT (from comment below): `/etc/httpd/conf/httpd.conf`:

```
<Directory "/var/www/html">
    Options Indexes FollowSymLinks
</Directory>

<VirtualHost *:80>
... server info ...
<Directory "/var/www/html/website/public_html">
AllowOverride All
Require all granted
Options -Indexes +FollowSymLinks
</Directory>
</VirtualHost>

```

.htaccess:

```
# Follow symbolic links in this directory.
Options +FollowSymLinks

```

# Answer
Finally managed to solve this. The entire purpose of this cloned server was to test out speed improvements from PHP-FPM. So since PHP evaluation is essentially offloaded to PHP-FPM, it doesn't matter if `httpd` has permissions, it matters whether the `php-fpm` process has permissions.

`ps aux | grep php-fpm` output:

```
root      5744  0.0  0.3 462268 14988 ?        Ss   16:45   0:00 php-fpm: master process (/etc/php-fpm.conf)
php-fpm   5745  0.0  0.9 467332 35196 ?        S    16:45   0:00 php-fpm: pool www
php-fpm   5746  0.0  0.4 466656 16528 ?        S    16:45   0:00 php-fpm: pool www
php-fpm   5747  0.0  0.3 466656 14032 ?        S    16:45   0:00 php-fpm: pool www
php-fpm   5748  0.0  0.3 466656 14028 ?        S    16:45   0:00 php-fpm: pool www

```

`groups php-fpm`:

```
php-fpm : php-fpm

```

So the ownership of my folder as `apache:web` is what doesn't fit. I just added the user `php-fpm` to the group `web` and changed things back to 775.

```
sudo usermod -aG web php-fpm

```

I would love comments on pros and cons of what I see as other possible solutions, especially from a security perspective:

1) Add `php-fpm` to the 'web' group.

2) Make `php-fpm` the owner, and httpd as member of `web` so it can still serve the files later.
> 0 votes

---
Tags: files
---


title: How to customize the xmlsitemap?

text:
# Question
Title: How to customize the xmlsitemap?
I installed the xmlsitemap module and would like to customize the sitemap.

For example, I would like to exclude some nodes that have a certain term reference field. I would also like to be able to create separate sitemaps for each content type.

Is there a way to do that? Otherwise I could probably generate the xml sitemaps with service\_views module.

# Answer
> 2 votes
You can do the same with xmlsitemap modules

Enable XML sitemap node, XML sitemap taxonomy submodules.

After that you will get these options.

# Answer
> 1 votes
You can use hook\_xmlsitemap\_link\_alter:

```
function hook_xmlsitemap_link_alter(array &$link, array $context) {
  $nid = $link['loc'];
  if ($nid == 'node/[:id]') {
    $link['status'] = 0;
    $link['access'] = 0;
  }
  }
}

```

---
Tags: 7, xml-sitemap
---


# Question
Title: Not able to access the key value of a list in a twig file
I'm trying to access the key of a list (Text) in a paragraph twig file

This is what I have in my list
small|Small Item
big|Big Item

```
{{content.field_option.0['#context'].value}}
{% set value = content.field_option.0['#markup'] %}
{{ value }}

```

I always got the text. Small Item or Big Item. I would like to obtain small or big of course depending of the user selection.

I'm going to use this value as an HTML Class.

Thanks for your help

# Answer
> 2 votes
I changed the `entity_view_display` of my paragraph so that my field output the key, instead of the value. I was then able to access the key. I hope that helps?

I'm able to use this: `content.field_button_chrome[0]['#markup']`

# Answer
> 1 votes
There are (at least) two options:

* Option 1: Change the Display of that field from default to key and use `{{ content.field_name.0 }}`
* Option 2: Do not use content settings and get the what the entity (paragraph, node etc.) sees: `{{ paragraph.field_name.0.value }}` for radio/select fields or for multi value fields:
```
{% for k,v in paragraph.field_variant %}
  {{ v.value }}
{% endfor %}

```

See also Getting Drupal 8 field values in Twig \> List \> Keys.

---
Tags: theming, hooks
---


# Question
Title: Get user list according to node field value
I have created one content type named "Project". I have added one field in it named "Skills". Skills is a multiple select field. And I have added one submit button. Which I want to use to get records of users. I have created an Ajax form submit, but my issue now is that I can't alter the form after the Ajax submit.

This is the code I'm currently using:

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

  if ($form_id == 'project_node_form') {

    $form['field_user_lists']['#access'] = FALSE;

    // Provide a submit button.
    $form['submit'] = [
      '#type'   => 'submit',
      '#value'  => 'Get Employee',
      '#weight' => '4',
      '#ajax'   => [
        'callback' => 'MYMODULE_form_ajax_submit',
        'wrapper'  => 'project_node_form',
        'method'   => 'replace',
        'effect'   => 'fade',
      ],
    ];

    $form['actions']['submit']['#submit'][] = '_custom_form_submit';
  }
}

function MYMODULE_form_ajax_submit($form, &$form_state) {

  if (!empty($form_state['input']['field_skills']['und'])) {

    //print_r($form_state['input']['field_skills']['und']); die();
    $query = db_select('field_revision_field_skillss', 'n');

    $query->join('users', 'u', 'n.entity_id = u.uid'); //JOIN node with users
    $query->groupBy('u.uid');//GROUP BY user ID
    $query->fields('u', ['uid', 'name'])//SELECT the fields from node
    ->condition('n.field_skillss_tid', $form_state['input']['field_skills']['und'], 'IN');

    $result = $query->execute();

    $form['field_user_lists']['#access'] = TRUE;

    while ($record = $result->fetchAssoc()) {
      print_r($record['name']);
    }
  }
  else {
    $output = 'Enter a value';
  }
}

```

# Answer
> 0 votes
I think you are getting close. When you use ajax in Drupal, you have to return a render array with commands. In your case it looks like you would want `ajax_command_replace`.

Two additional steps should get you up and running.

First, built an html string instead of using print\_r to try and send content back to the client.

```
    $return_html = '<div class="myclass">';
    while ($record = $result->fetchAssoc()) {
              $return_html.='<div class="my_user">' . $record['name'] . '</div>';
            }
    $return_html .= '</div>';

```

Then create the ajax object and render array to send back to the client

```
 $commands[] = ajax_command_replace('#my_selector', 'some html here');
 return array(
      '#type' => 'ajax',
      '#commands' => $commands,
    );

```

In this example, you would need to have a div on your page with an id of 'my\_selector' that would receive the new html.

---
Tags: 7
---


title: Difficulty adding a parent menu link

text:
# Question
Title: Difficulty adding a parent menu link
I'm creating a custom module in Drupal 8.4.4. I put several menu links under the `Development` menu.

```
scrape.scrape_form:
  title: 'Scrape'
  parent: system.admin_config_development
  route_name: scrape.scrape_form
  description: 'Scrape content from ccad.edu'
  weight: 10

scrape.scrape_images_form:
  title: 'Images Scrape'
  parent: system.admin_config_development
  route_name: scrape.scrape_images_form
  description: 'Scrape images from ccad.edu'
  weight: 20

...

```

This is working fine, but now that whole menu is getting a bit too long.

I wanted to wrap up all of my links under one 'header' link under the `Development` menu. I added this at the top of `mymodule.links.menu.yml`:

```
scrape.migration:
  title: 'Migration'
  description: 'Migration functions'
  parent: system.admin_config_development
  route:<nolink>
  menu_name: scrape.migration
  route_name: scrape.migration

```

But when I try to rebuild the cache, I get this error:

```
The website encountered an unexpected error. Please try again later. Symfony\Component\Routing\Exception\RouteNotFoundException: Route "scrape.migration" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName()

```

How can I make a new, non-navigable parent link under `Development`, to put my custom links under?

**Edit** 4k4's comment is correct, but my parent link is very small and greyed out.

```
scrape.migration:
  title: 'Migration'
  description: 'Migration functions'
  parent: system.admin_config_development
  menu_name: scrape.migration
  route_name: <nolink>

```

How can I get a full-height, dark-font header link?

# Answer
Instead of using `route_name: <nolink>`, I suggest providing a route for the link and e.g. pointing that route to Drupal's default overview page contoller. This should fix your issue and assures the users can click the menu link and get an overview of the available functions (e.g. when re-using your module in a Drupal that has no Admin Toolbar installed):

**mymodule.links.menu.yml**

```
scrape.migration:
  title: 'Migration'
  description: 'Migration functions'
  parent: system.admin_config_development
  route_name: scrape.migration

```

**mymodule.routing.yml**

```
scrape.migration:
  path: '/admin/config/development/scrape'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::overview'
    link_id: 'scrape.migration'
    _title: 'Migration'
  requirements:
    _permission: 'access administration pages'

```

You might have to adapt the path/permissions accordingly.
> 3 votes

# Answer
Just thought it would be easier to show a basic example that has both parent and submenu item in the mymodule.links.menu.yml.

Right now both links goto the same place (as I had to pick a default for the parent item, since I didn't have a admin page that lists all my custom links yet ... and also since having "route\_name: \<nolink\>" did not work for the parent menu item even though some peeps said it worked for them \[Note: using Drupal 8.6.12\]):

```
mymodule.parent:
  title: 'My MainMenu Link'
  parent: system.admin_config
  description: 'Custom main config menu item under the Admin->Configuration menu.'
  route_name: mymodule.form
  weight: 100

mymodule.parent_child:
  title: 'My Submenu Link'
  parent: mymodule.parent
  description: 'This is the sub-menu item for my custom config form.'
  route_name: mymodule.form
  weight: 101

```
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: Creating my own Sub-Menu / Parent in the Admin/Config menu
Is it possible to create my own Parent / Sub-Menu in the Configuration tab in Administration?

Every resource I find seems to give an example of the yaml file placing a link under the Development menu, with ***system.admin\_config\_development***, but I want one in (for example), ***system.admin\_config\_MYMENUNAME*** .

Example of current yaml file (hello\_world.links.menu.yml) :

```
hell_world.admin:
  title: 'Hello module settings'
  description: 'example of how to make an admin settings page link'
  parent: system.admin_config_development # want this to be system.admin_config_MYCUSTOMMENU
  route_name: hello_world.content
  weight: 100

```

# Answer
Just thought it would be easier to show a basic example that has both parent and submenu item in the mymodule.links.menu.yml.

Right now both links goto the same place (as I had to pick a default for the parent item, since I didn't have a admin page that lists all my custom links yet ... and also since having "route\_name: \<nolink\>" did not work for the parent menu item even though some peeps said it worked for them \[Note: using Drupal 8.6.12\]):

```
mymodule.parent:
  title: 'My MainMenu Link'
  parent: system.admin_config
  description: 'Custom main config menu item under the Admin->Configuration menu.'
  route_name: mymodule.form
  weight: 100

mymodule.parent_child:
  title: 'My Submenu Link'
  parent: mymodule.parent
  description: 'This is the sub-menu item for my custom config form.'
  route_name: mymodule.form
  weight: 101

```
> 5 votes

# Answer
Just use this parent route: **system.admin\_config** (/admin/config)

See example from Drupal core.

```
system.admin_config_search:
  title: 'Search and metadata'
  route_name: system.admin_config_search
  parent: system.admin_config
  description: 'Configure site search, metadata, and search engine optimization.'
  weight: -10

```
> 2 votes

---
Tags: 8
---


title: Why does updating break my site?

text:
# Question
Title: Why does updating break my site?
I have a site running Drupal 8.6.10.
I installed it with Composer: `composer create-project drupal-composer/drupal-project:8.x-dev JdP8M7b --stability dev --no-interaction`
I tried to update it to 8.6.12:

And now, I get an error when I go to any page using my default theme Mayo (no problem when I go to pages using admin theme Seven):

```
Le site Web a rencontré une erreur inattendue. Veuillez essayer de nouveau plus tard.</br></br><em class="placeholder">Twig\Error\SyntaxError</em>: An exception has been thrown during the compilation of a template ("Attribute "name" does not exist for Node "Twig\Node\CheckToStringNode".") in "themes/contrib/mayo/templates/block--system-menu-block.html.twig". in <em class="placeholder">Twig\Environment->compileSource()</em> (line <em class="placeholder">797</em> of <em class="placeholder">/Users/efalzon/Sites/JdP8M7b/vendor/twig/twig/src/Environment.php</em>). <pre class="backtrace">Drupal\Core\Template\TwigNodeTrans->compileString(Object) (Line: 37)
Drupal\Core\Template\TwigNodeTrans->compile(Object) (Line: 121)
Twig\Node\Node->compile(Object) (Line: 103)
Twig\Compiler->subcompile(Object) (Line: 38)
Twig\Node\BlockNode->compile(Object) (Line: 121)
Twig\Node\Node->compile(Object) (Line: 121)
Twig\Node\Node->compile(Object) (Line: 103)
Twig\Compiler->subcompile(Object) (Line: 108)
Twig\Node\ModuleNode->compileTemplate(Object) (Line: 78)
Twig\Node\ModuleNode->compile(Object) (Line: 92)
Twig\Compiler->compile(Object) (Line: 771)
Twig\Environment->compile(Object) (Line: 792)
Twig\Environment->compileSource(Object) (Line: 482)
Twig\Environment->loadClass('__TwigTemplate_b7128b0551d0a78f96214d3c3a23560aec4c9e673cc8d52ea34b27fddaa41d4c', 'themes/contrib/mayo/templates/block--system-menu-block.html.twig', NULL) (Line: 446)
Twig\Environment->loadTemplate('themes/contrib/mayo/templates/block--system-menu-block.html.twig') (Line: 64)
twig_render_template('themes/contrib/mayo/templates/block--system-menu-block.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('block', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 450)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 490)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 351)
__TwigTemplate_f653a38d19f626722860c776e638e47ff1e967a1bbf99439b558862341cf6bd3->doDisplay(Array, Array) (Line: 427)
Twig\Template->displayWithErrorHandling(Array, Array) (Line: 398)
Twig\Template->display(Array) (Line: 406)
Twig\Template->render(Array) (Line: 64)
twig_render_template('themes/contrib/mayo/templates/page.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('page', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 490)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 105)
__TwigTemplate_c0a9c9d745b014e5001be99f83f1adff9ca682260338f6d6a70aefea4539e7eb->doDisplay(Array, Array) (Line: 427)
Twig\Template->displayWithErrorHandling(Array, Array) (Line: 398)
Twig\Template->display(Array) (Line: 406)
Twig\Template->render(Array) (Line: 64)
twig_render_template('themes/contrib/mayo/templates/html.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('html', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 147)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 148)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)
</pre>

```

Any idea?

# Answer
> 0 votes
As an easy workaround you should try downgrading your twig

```
composer require twig/twig 1.37.1

```

Follow the discussion here and here for more up to date information.

---
Tags: 8, updating
---


# Question
Title: Get an Un-submitted/Active Form Field Value in $form_state?
I am unsure how to get unsubmitted/active form field values from a number/textfield into $form\_state. `field_count` could be saved as `4`, then is changed to `115`, how do I pass that change to $form\_state before a submit during `$form_state->setRebuild(TRUE);`?

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

  $config = $this->config('MYMODULE.settings');

  $form['#tree'] = TRUE;

  $form['fieldset'] = [
    '#type' => 'fieldset',
  ];

  $form['fieldset']['field_count'] = [
    '#type' => 'number',
    '#default_value' => $config->get('field_count') ?: 1,
  ];

  // This doesnt get a usable value.
  $form_state->set('field_count_state', $form['fieldset']['field_count']);

  $form['fieldset']['rebuild'] = [
    '#type' => 'submit',
    '#value' => 'Rebuild',
    '#submit' => ['::rebuildFormSubmit'],
  ];

  $form['fieldset'] = [
    '#type' => 'fieldset',
  ];

  for ($i = 0; $i < $config->get('field_count'); $i++) {

    $form['fieldset']['field'][$i] = [
      '#type' => 'textfield',
      '#default_value' => $config->get('field')[$i] ?: '',
    ];

  }

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

}

/**
 * {@inheritdoc}
 */
public function rebuildFormSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
  // ???.
  $this->messenger()->addMessage($form_state->get('field_count_state'));
}

```

# Answer
> 1 votes
**MYMODULE/src/Form.php**:

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

  // get form config.
  $config = $this->config('MYMODULE.settings');

  // Set our count. Used in for loop below.
  if (!empty($form_state->getValue(['fieldset', 'field_count']))) {
    // get $form_state count value.
    $defaultCount = $form_state->getValue(['fieldset', 'field_count']);
  }
  else {
    // Get config count value.
    $defaultCount = $config->get('field_count');
  }

  $form['#tree'] = TRUE;

  // Fieldset item.
  $form['fieldset'] = [
    '#type' => 'fieldset',
    '#prefix' => '<div id="fieldset-wrapper">',
    '#suffix' => '</div>',
  ];

  // Field count item.
  $form['fieldset']['field_count'] = [
    '#type' => 'number',
    '#title' => 'Number',
    '#required' => TRUE,
    '#default_value' => $config->get('field_count') ?: 1,
  ];

  // Rebuild submit item.
  $form['fieldset']['rebuild'] = [
    '#type' => 'submit',
    '#value' => 'Apply number',
    '#submit' => ['::rebuildFormSubmit'],
    '#ajax' => [
      'callback' => '::fieldCallback',
      'wrapper' => 'fieldset-wrapper',
    ],
  ];

  // Loop through our count and create form items.
  for ($i = 0; $i < $defaultCount; $i++) {

    $form['fieldset']['field'][$i] = [
      '#type' => 'textfield',
      '#default_value' => isset($config->get('script')[$i]) ? $config->get('script')[$i] : '',
    ];

  }

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

}

/**
 * {@inheritdoc}
 */
public function fieldCallback(array &$form, FormStateInterface $form_state) {
  return $form['fieldset'];
}

/**
 * {@inheritdoc}
 */
public function rebuildFormSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

```

This part in the `$form['fieldset']['rebuild']`:

```
'#ajax' => [
  'callback' => '::fieldCallback',
  'wrapper' => 'fieldset-wrapper',
],

```

along with:

```
/**
 * {@inheritdoc}
 */
public function fieldCallback(array &$form, FormStateInterface $form_state) {
  return $form['fieldset'];
}

```

Are the ajax options.

---
Tags: 8, forms
---


title: Get a views results programatically

text:
# Question
Title: Get a views results programatically
I have a page with a view on it and some exposed inputs. I need to get the results programatically. I can load a view programmatically no problem but setting the exposed input has not been working.

```
$view = Views::getView('inventory_listing');
$view->initDisplay();
$view->setExposedInput($view->getExposedInput());
$view->preExecute();
$view->execute();

```

results in ALL the rows, not the ones filtered out. I am running this in my hook\_form\_alter function because I need to change the display of my exposed filters. That may be part of the problem. Any ideas?

# Answer
I use direct input parameter for right filtering, and it is working for me.

```
$view = Views::getView('my_view_name');
$view->setDisplay('display_name_from_my_view');
$view->setArguments([ $value1, $value2 ]);
$view->execute();

```

So, i can take result of $view by

```
$result = [];
if (empty($view->build_info['fail']) and empty($view->build_info['denied'])) {
    $result = $view->result;
}

```

After this I can render it or use for another goal.
> 2 votes

---
Tags: views, 8
---


# Question
Title: How can I create a custom calculator on a drupal site?
What I want to do is have a page that collects a few pieces of information from the user and then calculates a result of a formula.

I do not want to store the information at all, and was thinking I may need to use the PHP Input type.

# Answer
> 4 votes
I see you've tagged this question with JavaScript, so it looks like you want to make a calculator using JavaScript.

To do this, you *could* make a custom module.

Create a module called calcform. Create calcform.js In your calcform.module you could create a custom block that has the calcform form.

You'll need to checkout: Creating modules | Block examples

```
function calcform_form(&$form, &$form_state){
  $form['number1'] = array(
    '#type'=>'textfield',
  );
  $form['number2'] = array(
    '#type'=>'textfield',
  );
  $form['calc_button'] = array(
    '#type'=>'button',
    '#value'=>'Calculate',
  );
  return $form;
}

```

Then in your JavaScript:

```
(function($){

  Drupal.calcform = {}

  Drupal.behaviors.calcform = {
    attach:function(){
      Drupal.calcform.bindEvents();
    }
  }

  Drupal.calcform.bindEvents = function(){

    $('#calc-button').click(function(e){
      // Prevent default button from submitting the form.
      e.preventDefault();
      // Do your magic here.
    });

  }

}(jQuery));

```

This is all very *pseudo-cody*, but it's the general idea. You actually don't need to write ANY JavaScript. You could create a form submit function that does the calculations and prints out the result to the form. You can then use the $form\['#ajax'\] capabilities to do all the magic for you.

Drupal is amazing like that.

# Answer
> 0 votes
You can do this online calculator in Drupal in several ways:

**Write from scratch**

For this we use plain JavaScript and, if necessary, the Drupal API itself. We add the usual form with the required fields and then, using the data entered into them by the user, we calculate using JavaScript using the given formula. If you need to send calculations to email, then you need to use PHP with the standard function mail () or SMTP or any modules to send data to email. As you know, this method requires considerable knowledge in programming.

**Ready Modules**

Perhaps there are several ready-made modules that allow you to make a calculation on Drupal, for example, Web Form Calculator and the like. However, they will have to be considerably refined for a specific calculator to use on your website. Obviously, this refinement will require a significant amount of time and skill.

**Online services**

You can choose a ready-made online designer to create a calculator and add it to the pages of the site. For example, JsCalc or uCalc. JsCalc will require some development skills to use the code. But uCalc can be used by people who do not own programming at all or do not want to waste time on development.

**Order the development of a calculator**

And the simplest but not cheap way, of course, is a simple calculator order from web studios and freelancers. This method is for those who have a budget for it.

In any case, I hope these lines will help novice developers to figure out which tool to create a calculator for them to choose :)

---
Tags: javascript
---


# Question
Title: Unlimited Custom Form Fields - Without Ajax
I have a simple form where users can set the number of fields they need. Users may need 100+ fields so I am not using ajax "add more" options.

With the below code, everything works (Even though you have to save the form twice, once to add the fields, twice to save the data), but I get an Undefined offset notice `Notice: Undefined offset: n` anytime I increase the field count and save the form.

As I'm not sure a better way to ask this question...

1) I know the code below is not perfect UX (having to save a form twice), does Drupal offer any API advantages to my approach I am not aware of?

2) Is there a way to handle/suppress these notices?

```
public function buildForm(array $form, FormStateInterface $form_state) {

  $config = $this->config('MYMODULE.settings');

  $form['#tree'] = TRUE;

  $form['fieldset'] = [
    '#type' => 'fieldset',
  ];

  $form['fieldset']['field_number'] = [
    '#type' => 'textfield',
    '#default_value' => $config->get('field_number') ?: 1,
  ];

  for ($i = 0; $i < $config->get('field_number'); $i++) {

    $form['fieldset']['field'][$i] = [
      '#type' => 'textfield',
      '#default_value' => $config->get('field')[$i] ?: '',
    ];

  }

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

public function submitForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();

  $this->configFactory->getEditable('MYMODULE.settings')
    ->set('field_number', $values['fieldset']['field_number'])
    ->set('field', $values['fieldset']['field'])
    ->save();

  parent::submitForm($form, $form_state);

}

```

# Answer
My issue was from improper checking of array key values. Below is the approach for non-ajax form adjustment (which is very similar to ajax).

**MYMODULE/src/Form.php**:

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

  // get form config.
  $config = $this->config('MYMODULE.settings');

  // Set our count. Used in for loop below.
  if (!empty($form_state->getValue(['fieldset', 'field_count']))) {
    // get $form_state count value.
    $defaultCount = $form_state->getValue(['fieldset', 'field_count']);
  }
  else {
    // Get config count value.
    $defaultCount = $config->get('field_count');
  }

  $form['#tree'] = TRUE;

  // Fieldset item.
  $form['fieldset'] = [
    '#type' => 'fieldset',
    '#prefix' => '<div id="fieldset-wrapper">',
    '#suffix' => '</div>',
  ];

  // Field count item.
  $form['fieldset']['field_count'] = [
    '#type' => 'number',
    '#title' => 'Number',
    '#required' => TRUE,
    '#default_value' => $config->get('field_count') ?: 1,
  ];

  // Rebuild submit item.
  $form['fieldset']['rebuild'] = [
    '#type' => 'submit',
    '#value' => 'Apply number',
    // Make our call to the rebuild function.
    '#submit' => ['::rebuildFormSubmit'],
  ];

  // Loop through our count and create form items.
  for ($i = 0; $i < $defaultCount; $i++) {

    $form['fieldset']['field'][$i] = [
      '#type' => 'textfield',
      // This is important. Must check isset() to avoid Undefined index notices.
      '#default_value' => isset($config->get('field')[$i]) ? $config->get('field')[$i] : '',
    ];

  }

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

}

/**
 * {@inheritdoc}
 */
public function rebuildFormSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

```

Related question: Get an Un-submitted/Active Form Field Value in $form\_state?.
> 1 votes

---
Tags: 8, forms
---


# Question
Title: View that shows all children content of parent
Been searching and cannot find this anywhere for Drupal 8. Very basic view request, can't figure out why it's not straightforward.

I want a View that shows Parent content and under it all Children content. Nothing to do with taxonomy, just want this to display in a view:

Parent Content 1
\- Child content 1
\- Child content 2
\- Child content 3

When trying a contextual filter, I get "This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'."

# Answer
> 0 votes
It doesn't seem your situation calls for contextual filters, you're not listing anything dependent on circumstances, you aim to list all of the Children, and group them by parent.

Since it's Children being referencing Parent nodes all you have to do to solve this is to a create Views that list Children, add the Parent field (the entity reference field you have on Child nodes), then under your `Format` settings set the `Grouping field Nr.1` to the Parent entity reference field. This is how you display the children nodes in a sort of a hierarchy based on which Parent they reference.

You can edit that Field settings if you want to `Exclude from display` and you can change the Style settings, the grouping output will take that into consideration most of the time.

---
Tags: views
---


# Question
Title: Add Fields to Field Group programatically
I have used "Field Group" module and created some groups in backend. Now i want to programatically add a field to the group. How can I do that.

I am using Hook\_form\_alter, I have noticed that every field has an 'und'attribute in which the field group it belongs to is listed, but if a create and 'und' array and add a field group name to it, it does not work.

How should I do it?

# Answer
> 21 votes
This is a bit old, but I wanted to do the same thing and couldn't find an answer on the web. I ended up figuring it out by myself.

Let's suppose you created a field group through the CMS interface with the name "group\_product\_fields". You added some fields to that group.

Now you have a new field being included in the form programatically via hook\_form\_alter. You want to add that field to "group\_product\_fields". Here is an example of what the field could be:

```
$form['new_product_field'] = array(
  '#type' => 'textfield',
  '#title' => t('New product field'),
  '#description' => t('Description for this new product field'),
);

```

All you need to do now is to add that new field to the field group. To do that add the line below to the hook\_form\_alter. It can be placed anywhere inside it.

```
$form['#group_children']['new_product_field'] = 'group_product_fields';

```

That's all. You may wish to adjust the field weight for it to be positioned as you want. But in the end this is really simple. :)

# Answer
> 6 votes
Quoting after Programtically add fields to a field group:

```
$groups = field_group_read_groups(array(
  'entity_type' => 'node',
  'bundle'      => 'article',
  'mode'   => 'full'
));
$your_group = $groups['node']['article']['form']['group_your_group'];
$your_group->children[] = 'field_your_new_field';
field_group_group_save($your_group);

```

# Answer
> 1 votes
Not sure how it worked for you. Because array key name must match with database field name. And They are:

> | entity\_type | varchar(32)
> | bundle | varchar(128)
>
> | mode | varchar(128)

I have to use following format to get it working. let me know if i am doing something silly here.

```
$groups = field_group_read_groups(array(
  'entity_type' => 'node',
  'bundle' => 'bundle type',
  'mode' => 'view_mode_name'));

```

# Answer
> 1 votes
Take a look at hook\_field\_group\_build\_pre\_render\_alter().

This provides you with an opportunity to change the structure of your groups programmatically.

For example, move the field "example\_field" **into** the group "group\_example" from the root form element:

```
function EXAMPLE_forms_field_group_build_pre_render_alter(&$form) {
  if (example_condition()) {
    $form['group_example'] = $form['group_example']['example_field'];
    unset($form['example_field']);
    // Further adjustments as necessary
  }
}

```

# Answer
> 0 votes
First, find your field group machine name in the CMS panel then in your form alter do

```
$form['#group_children']['FIELD_MACHINE_NAME'] = 'GROUP_MACHINE_NAME';

```

for an instanst, I've added a custom field mail into the `User form field group` field group :

```
$form['#group_children']['mail'] = 'group_user_form_field_group';

```

---
Tags: entities
---


title: Master list of contrib modules?

text:
# Question
Title: Master list of contrib modules?
Does there exist an updated master list of contrib modules in some easily parsed format (csv, json, xml ... whatever) that I can use for quick reference to see active full projects (not sandbox)?

I'm particularly interested in a list of **project names** and their **machine names**. I'm working on a custom module that may turn into a contrib module and I'd like to make sure my project name and machine name aren't already in use.

I know I can search here:

https://www.drupal.org/project/project\_module

But it'd save time if there was a list I could quickly reference. A quick Google search yielded no usable results in the first few pages.

# Answer
It will be a pretty big list, you could get all packages known by composer which should contain pretty much everything

```
composer show drupal/* --all

```
> 6 votes

# Answer
If you just need to know if a project machine name is already used, you can simply try the project URL for that machine name (`https://www.drupal.org/project/<project machine name>`). If you get a 404 error, it means the project doesn't exist, while a 403 error means the project exists but it's not visible to you.
This method doesn't help much if you want to know if there are projects with a similar machine name, if you don't want to try all the possible machine names that are too similar to the one you though to use.

What the Drupal.org REST API returns in https://www.drupal.org/api-d7/node.json?type=project\_module contains much information, even more than you probably need, but it's quite difficult to parse.

There are feeds for:

Unfortunately, they list only the new modules.

There is also a view listing all the projects, but (as far as I can see) it doesn't have a feed associated.

Depending on how you parse that list (Do you have a script extracting the project names and machine names?) you could either use the Drupal.org REST API or the view listing all the projects. The latter allows also to filter between full projects, sandboxes, and core compatibility.
> 4 votes

# Answer
Drupal.org has an API that exposes all node data. Among those nodes, are `project_module` nodes that are contrib module projects. The API is using the RESTful Web Services module so you can request an XML or JSON of the data:

* `https://www.drupal.org/api-d7/node.json?type=project_module`
* `https://www.drupal.org/api-d7/node.xml?type=project_module`
> 3 votes

# Answer
Why do you try to make simple things so complicated? As I understood, you just want to create single project (module), am I right?

So why don't you just put your desired project machine name at the end of this url, to check, whether it is already taken or not: https://www.drupal.org/project/YOUR\_COOL\_PROJECT\_MACHINE\_NAME

Also you can reference this page, to see all project's archives (and their names, obviously) - https://ftp.drupal.org/files/projects/
> 3 votes

---
Tags: community-official-site
---


title: Attach library to custom form

text:
# Question
Title: Attach library to custom form
I'm building a custom module (say 'mycalc') with a custom block with a custom form inside. Now I want to attach a library to the form and add some styling and live manipulation.

I created the mycalc.libraries.yml like this:

```
myform:
  version: 1.x
  css:
    theme:
      css/mycalc.css: {}
  js:
    js/mycalc.js: {}
  dependencies:
    - core/jquery

```

I added the js/mycalc.js and css/mycalc.css files with few basic lines. Then in the src/Form/MyCalcForm.php (where is set the MyCalcForm class), i edited the buildForm method adding this just before the return():

```
$form['#attached']['library'][] = 'mycalc/myform';

```

But there's no js nor css loading. What's wrong? Please help!

# Answer
First of all check for typos since, after failing to clear the cache is the most common mistake in this use case. After that, depending on your form base class attaching the library on the `::buildForm()` method should suffice. Also worth noting that perhaps another module (custom or contrib) could be messing with your form render array.

In the case you need to attach library to a form from core or third-party, you need to implement a `hook_form_alter()`:

```
/**
 * Implements hook_form_alter().
 */
function <YOUR_MODULE_NAME>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
    // If your library is intended to be used on specific form
    // check for it using the $form_id argument against your
    // form id which in most cases is returned by the ::getFormId()
    // method of your form.
    if ($form_id !== '<YOUR_FORM_ID'>) {
        // This is called eager return, is a technique
        // to avoid code nesting to improve code readability.
        return;
    }
    // To attach Blazy for example.
    $form['#attached']['library'][] = 'blazy/load';
    // To attach a library from a theme.
    $form['#attached']['library'][] = '<YOUR_THEME_NAME>/<library_name>';
    // To attach a library from a module.
    $form['#attached']['library'][] = '<YOUR_MODULE_NAME>/<library_name>';
    // Pass even variable from this function to JS settings
    $form['#attached']['drupalSettings']['<YOUR_MODULE_NAME>']['variable'] = 'PHP Value To JS';

    return $form;
}

```

If you pass variable with above mentioned method - `$form['#attached']['drupalSettings']['<YOUR....` then that variable will be available in your JS file.

```
(function ($, Drupal) {
  'use strict';

  Drupal.behaviors.<YOUR_MODULE_NAME> = {
    attach: function (context, settings) {
       console.log(settings);
       console.log(settings.variable); //Should log variable value
    }
  };
})(jQuery, Drupal);

```

Add javascript to form by module
> 11 votes

---
Tags: 8, forms
---


title: Increase label max length

text:
# Question
Title: Increase label max length
The default max length for all labels of all field types is 128. The DB can handle 255. So no schema change. How can I change the default max length to 250?

I've seen this module https://www.drupal.org/project/remove\_field\_label\_length\_limit

> Removes field label length limit (which is 128 characters). The module supports entity field labels, field group labels, and views field labels.

it was working on Drupl7 very well. but there is no version for Drupal 8.

I'm looking for a way to increase all Label length in a specified content type.

# Answer
use Change Label Length limit module.

**it lets users change the maximum limit of label fields.**
> 2 votes

---
Tags: 8, forms
---


# Question
Title: Host doesn't support nested folder structures for deployment. How do I adjust Composer?
So, I have to deploy a drupal 8 site to a host which doesn't provide functionality to specify an entry point for a Drupal site which is nested below the site root folder. How can I update the folder structure to have everything in the server's site root? What I tried initially was to move the contents of the `site_root/web/` folder up to the site root, but this causes 500 errors. I'm not sure since I can't see the errors on the host server, but replicating the scenario on my dev machine points to the autoloader.php file looking in the wrong place `PHP Fatal error: require(): Failed opening required '/var/www/html/ab-test/../vendor/autoload.php'`.

I have tried to resolve this by first following the suggestion to re-run `composer install` from the site root but that doesn't seem to help. When I manually update where the autoloader.php should be looking, I then get this error`PHP Warning: require(/var/www/html/ab-test/vendor/composer/../../load.environment.php)` which again suggests that the file/folder structure is being set somewhere I'm not thinking of or don't have enough experience to check. So, my convoluted question comes down to how do I switch from a nested to a non-nested folder structure without everything freaking out?

# Answer
> 1 votes
As you are using an Apache server, you may try to set the Drupal root folder using an `.htaccess` file in your site\_root:

```
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{REQUEST_URI} !web/
RewriteRule (.*) /web/$1 [L]

```

(Replace `example.com` with your actual domain name.)

This way, you can keep the "nested" folder structure created using Composer and serve all requests for your domain with the `web` sub folder.

---
Tags: 8, composer, deployment
---


title: How do I get the user avatar picture?

text:
# Question
Title: How do I get the user avatar picture?
I am working on a custom Drupal 8 theme and I am trying to get the user avatar picture on a variable and output somewhere in the HTML.

I have created this function to get the name & email of the current user logged in like so:

```
#Function to get the user name value & output in the HTML DOM
function tropical_preprocess_page(&$variables){
  # gets current user name
  $user_logged_in_name = $variables['user']->getDisplayName();

  # creates value to ouput in the DOM & capitalize first letter
  $variables['user_logged_in_name'] = ucfirst($user_logged_in_name);

  # gets user email
  $user_email = $variables['user']->getEmail();
  $variables['user_email'] = $user_email;
}

```

That worked perfectly! Now I am trying to get the user profile picture, but I am not able to do it. Any help will be appreciate it.

# Answer
> 4 votes
you can get Url it by `get('user_picture')->entity->url()`( you can get URI too with `get('user_picture')->entity->getFileUri()`), So

```
function tropical_preprocess_page(&$variables){
  // gets current user name
  $user_logged_in_name = $variables['user']->getDisplayName();

  // creates value to ouput in the DOM & capitalize first letter
  $variables['user_logged_in_name'] = ucfirst($user_logged_in_name);

  // gets user email
  $user_email = $variables['user']->getEmail();
  $variables['user_email'] = $user_email;

  // get user picture
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())
  $variables['user_picture'] = $user->get('user_picture')->entity->url();

}

```

Additionally, If you want to get the default image when the user account doesn't have an image associated, use the following code.

```
$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$picture = file_create_url($file->getFileUri());

```

---
Tags: theming
---


title: Show count in view grouping

text:
# Question
Title: Show count in view grouping
I'm building a index view to use as search. I'm grouping the results by a term field and everything works fine. What I want to do is add a count after the group title to show how many results that exists with this term.

Can't find a way to do this in drupal 8 so I'm asking you. I've google for half a day without finding anything.

# Answer
Using this answer as a base you can add views\_field\_view to include a view of content filtered by term.

In more details

# 1. Create a view of terms that includes count of content using each term

* Create a view that displays *terms*
* enable *aggregation*
* add relationship *Content with term*
* add sort *content uuid* with *aggregation type: count* (optional)
* add field *content uuid* with *aggregation type: count*
* add field *taxonomy term*

Your view should look similar to the following

# 2. Create a view that will display the content

* Include contextual filter on the vocabulary of your interest (*tags* in this case)
* Add any filters or fields that you need

This view will look similar to

# 3. Add last view as a field to first view (step 1.)

* Download and enable **views\_field\_view** module
* Go to view from step 1. and
    + add field *Taxonomy term: Term ID*
    + add field *Global view* ) (made available from *views\_field\_view*)
    + on the settings find the view from step 2.
    + use `{{ raw_fields.tid }}` as *contextual filter*

Next screenshot shows the changes from original view and settings for *view field*

**You are done**

Your view now should display the terms with count and all the content that have used it.
> 3 votes

---
Tags: views, 8
---


# Question
Title: How to use Interface Translation for specific text on specific pages only
I need to translate certain text in a twig template to one of several languages, depending on the Language selected for the node being displayed. I've installed the Interface Translation module (without translation files because I don't want the interface translated) and added custom translations for the text I want translated. This works perfectly using {{ "text to translate"|t }} in the template.

Here's the problem: When I'm at a page like "/es/node/50" (Spanish), Drupal "shifts to /es mode" by adding /es to menu entries, admin links, etc. I assume this is expected, but I don't want it. I simply want to use Drupal's built-in translation capability (via |t) to translate things I specify. I don't want any other pages to get an /es prefix.

I want to select a language for a node and then have translation capacity for that node's template only, without affecting anything else in the site.

Is this simply outside the use case for the Interface Translation module? Or is there a combination of modules/settings to make it possible?

I've fiddled with this for hours (days) and have read documentation and many posts without success.

# Answer
> 1 votes
Drupal has very advanced Multi-lingual capabilities, so it's safe to assume that you can configure your site according to your needs. You just have to learn a bit about Drupal multilingual fundamentals and see how your needs fit in there.

It seems your question is about how languages are selected and displayed, and not about Interface translation. You probably already understand the difference between content and interface, and that the strings you put into the templates are part of the interface. And you probably want to be able to view content in different languages while keeping the interface language the same.

Under `Configuration > Regional and language > Languages > Detection and selection` you can choose to set that your Content language selection should work differently from the Interface language selection.

Enable that option **Customize Content language detection to differ from Interface text language detection settings** and then also enable the **Content language** Detection method (Determines the content language from a request parameter.) and it should be ordered to be your first enabled method.

This way you will be able to view Spanish nodes while keeping the English interface. This is happening through the parameter that is being added to the URL. Instead of:

`/es/node/50`

you will have:

`/node/50?language_content_entity=es`

With interface language kept as English, your menus and other links will lead to the English side of things, but you will be able to view translated content.

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


# Question
Title: Selecting the number of Records from Textbox
I am trying to built a text box where I can type in the number of records that I want to select. So if I type in "100" the first 100 records should be selected and then will assign it to user. How do I make built this text box where it would select first 100 nodes and then perform the action of assigning it to user.

# Answer
IIRC you could build this type of an Entity reference field with the help of Entity reference Views Display in Drupal 7 and the Entity Reference View Widget module.

In Drupal 8 you probably need the wonderful Entity Browser that is usually used to manage media files, but no reason not to use it for any other entity references. So you still need the Entity reference field, you just use the Entity Browser as the widget for that field to control how the choices are presented.

You'll probably want a filter above your results to list a certain number of results (100 for example) and then a "Select all" option to select all the results that have been filtered out (table display may come with that already).
> 0 votes

---
Tags: views
---


# Question
Title: Behaviors are only called the first time a view is loaded
On a Drupal 8 site I have a world map where the user can click on a country; a view with content is then loaded with AJAX using a custom module and the following JavaScript.

```
(function($, Drupal, drupalSettings, window, document) {
  Drupal.behaviors.worldmap = {
    attach(context, settings) {
      console.log('behaviors called');
      $('#map-container', context).once('addmap').each( () => {
        let map = new InteractiveMap('.interactive-map', (country) => {
          let id = settings.worldmap.yearsnids[country];
          if(!id) {
            id = 0;
          }
          console.log('id');
          let ajax_settings = {
            url: '/my_module/ajax/expand/' +
                  settings.worldmap.ctype + "-infobox/" + id,
          };
          Drupal.ajax(ajax_settings).execute();
        });
        map.init();
      });
...

```

I have a custom template for the view where I add a ajax link.

```
<a href="/my_module/ajax/expand/{{ fields.field_content_type.content|render|striptags|trim }}/{{ fields.nid.content|render|striptags|trim }}" class="button use-ajax">See the project</a>

```

Clicking that link loads another view with more content. So basically a preview is loaded when the user clicks on a country, and a link in the preview then loads the full content if clicked.

Both the preview and the content (also a view), is loaded from my\_module with an AjaxResponse:

```
namespace Drupal\my_module\Controller;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Controller\ControllerBase;

class my_moduleController extends ControllerBase {
  public function loadContent($method, $action, $type, $nid) {
    $response = new AjaxResponse();
    // logic to determine which action and type we want to load
     ...
    $build['view'] = [
      '#type' => 'view',
      '#name' => $viewname,
      '#display_id' => $did,
      '#arguments' => [$nid],
    ];
    $response->addCommand(new ReplaceCommand($replaceClass,
                          $build, ['fadeIn']));
    return $response;
  }
}

```

This all works, but the link in the preview only works for the first preview loaded. In every other preview loaded, clicking the link sends the user to the actual ajax-path (eg. mysite.com/my\_module/ajax/expand/my\_ctype-infobox/the\_actual\_id), and the content that should have been rendered to the page are displayed like json in a textbox:

```
[{"command":"settings","settings":{"pluralDelimiter":"\u0003","ajaxPageState":
...

```

When the page with the map is loaded, and first time the preview is loaded, 'behaviors called' prints to the console - the link to load the full content works. On subsequent times, clicking on a country loads the preview, but behaviors aren't called at all. 'id' gets printed to the console every time I click.

This is the HTML structure:

```
<div class="interactive-map">
   <div id="map-container"></div>
   <div class="info-box">
     <div class="info-box__content">
        <div class="placeholder"></div>
    </div>
  </div>
</div>
<div class="full-content-wrapper">
  <div class="placeholder"></div>
</div>

```

The preview is loaded into the info-box\__content div, which is outside the #map-container.

# Answer
> -1 votes
The Root of the problem is the ReplaceCommand in the ajaxResponse.

By reading the issue that I mentioned in my comment, I realized the root of my problem is probably the same as in that issue.

When the preview is loaded the first time by clicking a country, all behaviors are attached correctly to the new div inside .info-box\__content.

The next time a preview is loaded, that new div inside .info-box\__content is replaced by another via the ReplaceCommand. `Drupal.behaviors.worldmap` tries to attach the behaviors again, but, for reasons I don't quite know, it tries to attach it to the old div that was just removed by the ReplaceCommand, and thus it fails (silently).

At least this is what I think is going on. To work around that issue, I simply remove any old div and add a new placeholder before the ajax execute call - my javascript now looks like this:

```
(function($, Drupal, drupalSettings, window, document) {
  Drupal.behaviors.worldmap = {
    attach(context, settings) {
      console.log('behaviors called');
      $('#map-container', context).once('addmap').each( () => {
        let map = new InteractiveMap('.interactive-map', (country) => {
          let id = settings.worldmap.yearsnids[country];
          if(!id) {
            id = 0;
          }
          console.log('id');
          let ajax_settings = {
            url: '/my_module/ajax/expand/' +
                  settings.worldmap.ctype + "-infobox/" + id,
          };
          // new code for removing old div and adding new placeholder
          $('.info-box__content div', context).remove();
          $('.info-box__content', context).html('<div class="placeholder"></div>');
          Drupal.ajax(ajax_settings).execute();
        });
        map.init();
      });
...

```

And now it works :)

# Answer
> 1 votes
Your "once()" function is called on an element with an ID. If your HTML is valid there can be only one such element in the DOM.

What happens with the once() function is that it adds a class to the element which marks it as processed. If the once() function is called again on the same element, it will do nothing. So looking at your code, it does indeed seem it will call the each() function just once on first loading, then never again.

It is right to use the once() function in this situation but you probably want to use a selector representing the children that can be dynamically created. I can't really advise what that should be without seeing the actual HTML.

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


# Question
Title: How do I add custom pages or view pages to search index?
Suppose I have a custom page built in a custom controller. Or similarly, a view page the displays the list of nodes, such as the classic "admin/content" page.

I want certain user roles to be able to find this page when they search the site. The search does not have to index the entire view/page content, but rather a select parts of the content.

Is this possible to do using core hooks? If not, then perhaps using search api hooks? I am thinking of hooking into the indexing process, and then, retrieve the pages I want to index and send them along. But I am not sure how to do this in a abstract manner where the implementation would work using core database search or search api with solr.

Note Drupal 7 or 8 ideas would be much appreciated.

# Answer
Yes, it's possible to provide a custom search index for either the Core/Search API module. Both modules are using the D8 plugin API to create their own plugin types for providing new indexing.

* In Core, the `SearchPlugin` plugin type allows you to define the methods that you will need to implement for all aspects of search. To see how this works, look at the core `UserSearch` & `NodeSearch` plugins to see how it interfaces with queries and indexing.
* For SearchAPI, there are many different plugin types for interfacing with its different aspects of search. For brevity, you should start looking at the `SearchApiDatasource` plugin type to start providing a new indexable source.

In regards to an "abstract manner where the implementation would work using core database search or search api with solr," you're going to have to get clever with OOP and the plugin classes you're providing in your module if you want to do something like that. You're better off implementing each first, then abstracting later (if it provides benefits).
> 1 votes

---
Tags: 8, views, search
---


title: Set max_execution_time for view?

text:
# Question
Title: Set max_execution_time for view?
I've got a view that generates a CSV report on user information. However, due to the size of the dataset it's causing the server to timeout. Is there some way that I can set the `max_execution_time()` or `set_time_limit()` just for this path?

# Answer
> 1 votes
If you're looking for a custom-code centric path. Both D7 & D8 provide a `hook_views_pre_execute()` hook. It will trigger prior to any view query execution.

You can hook into this function, inspect `$view` object for the particular view you're wanting to extend your PHP execution, then call the PHP function of your choice.

---
Tags: 7, views, configuration
---


title: Shared Field Name Between Entity Types?

text:
# Question
Title: Shared Field Name Between Entity Types?
I have always separated my field names by entity. e.g.

`field_paragraph_h2` or `field_content_h2`,

but when you look at config, fields are designated by their entity type as well.

`field.field.paragraph.paragraph_type.field_paragraph_h2` or `field.field.node.content_type.field_content_h2`

Am I safe using just `field_h2` for both entity type field names, or are there instances with Drupal where this may be problematic?

e.g.

`field.field.paragraph.paragraph_type.field_h2` or `field.field.node.content_type.field_h2`

# Answer
You are safe to use the same name. The fields are unique for each entity type, even when they have the same name.

They have their own field storage configuration, instances and will be stored to dedicated database tables per entity type.
> 3 votes

---
Tags: 8, configuration
---


# Question
Title: How do I retrieve media from a reference field?
Inside a node type, I have a reference field to target a media. With a db select, I need to load all related medias of the nodes. For this I use this code:

```
$database = \Drupal::database();
$result = $database->select('media_field_data', 'm')
->fields('m', ['mid'])
->condition('m.bundle', 'gallery')
->leftjoin('node__field_related_gallery', 'n', 'media_field_data.mid = node__field_related_gallery.field_related_gallery_target_id')
->leftjoin('field_related_gallery_media_field_data', 'd', 'node__field_related_gallery.entity_id = field_related_gallery_media_field_data.nid')
->range(0, 5)
->execute()
->fetchAllKeyed(0, 0);
dpm($result);

```

But with this code I get an error and don't get the related mids. If I remove the line with the leftjoin I get the mids.

How can I proceed to verify if a media is related to a node and get only the media with a related node?

With views I can get easily the results with this query:

```
SELECT media_field_data.mid AS mid,
field_related_gallery_media_field_data.nid AS
field_related_gallery_media_field_data_nid
FROM
{media_field_data} media_field_data
LEFT JOIN {node__field_related_gallery} node__field_related_gallery ON
 media_field_data.mid =
 node__field_related_gallery.field_related_gallery_target_id AND
 node__field_related_gallery.deleted = '0'
 LEFT JOIN {node_field_data} field_related_gallery_media_field_data ON
 node__field_related_gallery.entity_id =
 field_related_gallery_media_field_data.nid
 WHERE (media_field_data.status = '1') AND (media_field_data.bundle IN
 ('gallery')) AND (field_related_gallery_media_field_data.nid IS NOT NULL)
 LIMIT 26 OFFSET 0

```

Thanks.

# Answer
Do you have to do it with a DB call? Why not use Drupal's existing functions?

```
  // Load a node by node ID.
  $nid = '213';
  $node = \Drupal\node\Entity\Node::load($nid);

  // OR load current node.
  $node = \Drupal::routeMatch()->getParameter('node');

  if (!empty($node)) {
    // Assumes you have a media field called "Related gallery"
    $medias = $node->get('field_related_gallery')->referencedEntities();

    foreach ($medias as $media) {
      // Do stuff with the media.
    }
  }

```
> 0 votes

---
Tags: entities, database
---


# Question
Title: Get a list of field variables for template code
For Drupal 7, how do I access (or generate) a list of all the field variables available for building a template (for a given content type)?

Some context: I used to rely on the (now deprecated) Contemplate module to write my templates. Directly within its interface, it would print a list of all of the available variables, like this.

It was quite handy. Now that I'm making disk-based templates and do not have this list generated by the Contemplate module, I'm confused as to how I might produce something similar for use as a reference.

# Answer
> 1 votes
Use Devel module and then with using get\_defined\_vars you can get a list of defined variables. then in you template file use the following snippet

```
<?php
 dsm(get_defined_vars());
// or even  dsm(get_defined_vars());
?>

```

and another solution is based on `hook_preprocess`. just dumps the variables there.

**on your template.theme file**

```
mymodule_preprocess(&$vars, $hook) {
dpm($vars);
}

```

\**Update\* if you want to see the $variables on node template try on your template.

**copy/paste this snippet on your `template.php` then clear the cache** function YOURTHEMENAME\_preprocess\_node(&$variables) { dpm($variables); // you can add or remove whatever you want to it here }

if your theme name is `themetastic` So

```
function themetastic_preprocess_node(&$variables) {
    dpm($variables);
    // you can add or remove whatever you want to it here
}

```

Ref: Read this to learn more about preprocessing

---
Tags: theming
---


# Question
Title: How do I display a block on the checkout page based on the product type?
I have created some custom blocks in code that are shown on the Drupal Commerce checkout page. I would like the block to have differ content basing on which items are in the cart. How can I achieve this in code?

# Answer
Around the time some ***Item1*** (or ***Item2***) is added to your cart, grant that user access to a role like "***HasItem1InCart***" (or "***HasItem2InCart***"). Use the Rules module to grant such access, using a Rules Action like "Add user role".

Within the block visibility settings for ***Block1*** (which you want to show if Item1 is in the cart), only show that block to users with roles ... you probably guessed it .... ***HasItem1InCart*** (same for ***Block2*** and ***HasItem2InCart***).
> 0 votes

# Answer
Based on what I can gather from your question, You could use preprocess\_page() hook on the checkout page and load the custom blocks there.

This way you can supply some kind of input to the block based on the page content(based on the items in the cart). Then you can change the block content based on the input given to the block.
> 0 votes

---
Tags: blocks, commerce
---


title: Adding Constraint to Paragraph field

text:
# Question
Title: Adding Constraint to Paragraph field
I have a Content Type with a field that references 6 different paragraph types. The field is set up to accept unlimited values. For one of the types I would like to have exactly four values added. I've been trying to add a Constraint but it seems that Constraints are built to check if a fields values are valid and not if there are only four items

Is using hook\_entity\_bundle\_field\_info\_alter the correct hook or should I be focused on using hook\_entity\_type\_alter or maybe even some other method?

# Answer
> 4 votes
Yes, use `hook_entity_bundle_field_info_alter` and when you add a constraint to the field (and not to a item or property), your constraint gets the entire field item list, so you can check how many items you have of which type, see FieldConfigInterface::addConstraint:

```
function mymodule_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node' && $bundle == 'page') {
    $fields['field_paragraph']->addConstraint('MymoduleParagraphTypes');
  }
}

```

Example for a constraint restricting the field to four paragraph items of a specific type:

```
  public function validate($items, Constraint $constraint) {
    $paragraphs = array_filter($items->referencedEntities(), function ($paragraph) {
      return $paragraph->bundle() === 'image';
    });
    if (!empty($paragraphs) && count($paragraphs) != 4) {
      $this->context->addViolation($constraint->errorMessage);
    }
  }

```

You can generate the constraint with the Drush command:

```
drush generate plugin-constraint

```

---

Edit: If you need to check field values inside of the paragraphs then use $item-\>entity. See How to validate a paragraph field?

---
Tags: forms, paragraphs
---


title: Unable to create an admin menu link

text:
# Question
Title: Unable to create an admin menu link
I am trying to create a menu link in Drupal 8. I am following this document: https://api.drupal.org/api/drupal/core!includes!menu.inc/group/menu/8

My module name is twitter\_pull and I was able to create the path fine, and it loads a form on that page, I just can't get it display a menu link. I have tried flushing the caches but that didn't do anything. Here is my code:

Inside my twitter\_pull.routing.yml

```
twitter_pull.settings:
  path: 'admin/config/services/twitter-settings'
  defaults:
    _form: '\Drupal\twitter_pull\Form\TwitterSettingsForm'
  requirements:
    _permission: 'administer site configuration'

```

Inside my twitter\_pull.links.menu.yml

```
twitter_pull.settings:
  title: 'Twitter settings'
  description: 'Twitter settings for your site'
  parent: system.admin_config_services
  route_name: twitter_pull.settings
  weight: 100
  #Use menu_name when you want to add your link to a non-system menu.
  #menu_name: devel

```

# Answer
It looks like you are using an older version of Drupal core. Upgrade to one of the betas or the latest 8.0.x from Git and it should work fine.

In the latest versions the filenames have been changed, as reported in YAML files for menu links, contextual links, local tasks, and local actions have been renamed. 8.0.0-alpha14 is the first tagged release with the filename change.
> 2 votes

# Answer
Its because of incorrect file name issues. I also faced the same kind of issues and after analysis I got to know, I was did a minor mistake on the file name( 's' got added additionally ). Like: twitter\_pulls.links.menu.yml instead twitter\_pull.links.menu.yml

twitter\_pull.links.menu.yml twitter\_pulls.links.menu.yml

Thanks
> -2 votes

---
Tags: routes, 8
---


# Question
Title: If admin theme is 'seven' disable the module
So in a custom module, I'd like to check whether the theme is seven or not, if it's seven the module shouldn't load/work.

Note: I have a module that shouldn't override half of UI of seven theme but should work if it's any other theme, played around with theme.manager for now but still struggling.

# Answer
Create custom EventSusbcriber ( read this for more information )

then check if the current theme is `seven` with and `MODULE_NAME` is enabled

```
  $moduleHandler = \Drupal::service('module_handler');
    if (\Drupal::service('theme.manager')->getActiveTheme()=='seven' && $moduleHandler->moduleExists('MODULE_NAME')){

```

then try to uninstall with

```
    $moduleHandler->uninstall(['MODULE_NAME']);

```

**Finally, The total solution should be something like**

```
  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events['kernel.request'] = ['uninstallModuleIfThemeIsSeven'];

    return $events;
  }

  /**
   * This method is called whenever the kernel.request event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function uninstallModuleIfThemeIsSeven(GetResponseEvent $event) {
  $moduleHandler = \Drupal::service('module_handler');
    if (\Drupal::service('theme.manager')->getActiveTheme()=='seven' && $moduleHandler->moduleExists('MODULE_NAME')){
        $moduleHandler->uninstall(['MODULE_NAME']);
    }

  }

```
> 1 votes

---
Tags: 8, hooks
---


# Question
Title: how to exclude PHPUnit based functional tests from runnning?
I am trying to run only unit test for my custom module.

`./vendor/bin/phpunit -c ./web/core ./web/modules/custom/testing_example --testsuite=unit` .
But I keep getting the following error:

There were 2 errors: `1) Drupal\Tests\testing_example\Kernel\ExampleFixtureManagementTest::testNodeCreation
Exception: There is no database connection so no tests can be run. You must provide a SIMPLETEST_DB environment variable to run PHPUnit based functional tests outside of run-tests.sh. See https://www.drupal.org/node/2116263#skipped-tests for more information.`

I only want to run PhpUnit tests and not functional/browser tests.

# Answer
> 0 votes
Since those tests are grouped by namespace/directory, you can just pass the respective path to phpunit, simply add `tests/src/Unit` to your existing path.

# Answer
> 0 votes
To run only certain tests in phpunit, append `--filter` (https://phpunit.de/manual/6.5/en/textui.html) in your phpunit call whether directly in cli or in an IDE phpunit config.

To filter to only Unit tests *across all modules* but exclude Functional and Kernel tests, you can pass in something that matches the well-structured Drupal tests path like @Berdir was getting at like `--filter Unit`.

I suspect there's a more specific way to narrow it down like `--filter tests/src/Unit` but I didn't figure it out. I assume one can also combine filters to pick and chose among Unit and Kernel, for instance, but I also didn't play with that. :)

---
Tags: 8, testing
---


title: Using Views to categorize results

text:
# Question
Title: Using Views to categorize results
I have a view which is returning integers. Instead of presenting the actual values, I'd like to replace them with the name of a category. For example, all of smaller numbers (\<100) are to be returned as "low", mid-range results (101 - 999) will say "moderate," and large values (\>1000) to read as "large". Is this possible? Thanks

# Answer
Views Conditional (https://www.drupal.org/project/views\_conditional) which has stable releases for D7 and D8 will do this.

IF/ELSE is readily apparent when using this module. To achieve what I desired, I created two conditional fields:

Views: Views Conditional (If field\_number is Less than 100, output Low, else output Moderate)

and

Views: Views Conditional (If field\_number is Greater than 1000, output Large, else output \[views\_conditional\] )

Then exclude the first conditional field from display.
> 2 votes

---
Tags: views
---


# Question
Title: How do I programmatically update a UUID?
**Reason:** Receiving uid does not exist error. Upon investigating, this error appears only when we edit or save the preexisting columns paragraph. If we create new columns paragraph, the error doesn't appear as the uuid is different for the newly created columns paragraph.

This is the reason to update the uuid for a paragraph that is referenced on that page. In my custom module I have loaded all nodes using entity query below and loaded the referenced paragraph.

```
$nids = \Drupal::entityQuery('node')
  ->condition('type', 'page')
  ->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

  foreach ($nodes as $n) {
   //Relevant apragraph for the content type
   $para = $n->get('field_page_content')->getValue();
   $para_2 = $n->get('field_banner_image')->getValue();

   foreach($para as $e){
     $p = \Drupal\paragraphs\Entity\Paragraph::load($e['target_id']);

    if($p->bundle() == "columns"){
      kint($p,'Paragraph Entity');
      kint($p->uuid(),'Paragraph UUID');

       $uuid = 'd12da227-890b-4eb7-86b1-93937e7d6d91';

       //save paragraph
       //$p->save();

    }
  }
}

```

How can I get this updated without recreating the columns paragraph as there are quite a few.

# Answer
This is the route to go if you must add the uuid in this manner.

```
$uuid = 'd12da227-890b-4eb7-86b1-93937e7d6d91';
$p->set('uuid',$uuid);
$p->save();

```
> 2 votes

---
Tags: 8, paragraphs
---


# Question
Title: Can I safely delete the migrate tables after migration?
I passed a site from d7 to d8 I wanted to know if I can delete tables db migrate map d7 and migrate messages d7 they are more than a hundred I can delete db tables migrate map d7 and migrate d7 messages of types of content that no longer exist on d8?

http://fortecad.altervista.org/ottomigratemapImmagine.jpg

http://fortecad.altervista.org/ottomigratemessaggeImmagine.jpg

regards

# Answer
> 5 votes
Yes. If you're doing a "one-and-done" migration you can remove the tables. Just make sure to:

* uninstall the migration modules
* remove your relevant migration config
* then remove your DB tables once you have no code/config dependant on these tables.

Note, the caveat is you're wiping out your migration history.

The migration framework has an ongoing issue about this topic. These tables are persisted since these they capture migration source/destination metadata. The metadata is important if you have a phased, or ongoing, migration. If your migration project is over, the metadata has no relevance.

---
Tags: 8, migrations
---


# Question
Title: Send "Views PDF Display" generated PDF by mail as attachment
TLDR: How to send Module "Views PDF Display" generated PDF by mail as attachment without another deprecated module ?

I have a Drupal site with the Views PDF Display module on it.

I can generate a custom PDF for my order, and all is nice, except for one things. I need to send those PDF one by one by mail as attached file for the past year of commands, and i looked around for a while without seeing an answer.

I found that one the module page, they talk about two modules that does that, but the fact that both modules are 7 years old and thus not covered by security policy is a 'no'

Other idea to generate all PDF from the last year is just not possible as it will be too much PDF for the server to handle

Do you have any idea for me to retrieve those PDF from the views and to send them by mail as an attachment ?

# Answer
I tried a couple of things with views directly, but I had no luck, so I turned to curl. You can create your pdf display and give it a path. Hit that path with curl to download the file that will be generated by your view. My example below is pretty simple, but you can pass arguments with the url just like you would normally.

```
 $pdf_page = "http://yourplace.net/pdf";
  $pdf_file = fopen('/tmp/my.pdf', 'w');
  $ch = curl_init($pdf_page);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_FILE, $pdf_file);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_exec($ch);
  curl_close($ch);
  fclose($pdf_file);

```

I tested this with a pdf display built on Views PDF and it worked well. Maybe someone has an answer that utilizes views directly instead of using curl.
> 0 votes

---
Tags: 7, views, emails
---


# Question
Title: Drupal Commerce custom pane as payment and shipping address
Currently, Drupal Commerce does not have a solution for "shipping address is the same as payment address" checkbox, which is very unlucky. I was thinking of creating a custom pane with my custom addresses form, where I could easily create such a checkbox. However, I could not find anywhere how to trigger a payment (from commerce payment module) after the addresses form is successfully submitted. Could you help me? Thanks!

# Answer
> 1 votes
This feature does not exist in core yet but it is in progress right now. Look for it in Commerce 2.13.

---
Tags: 8, commerce
---


title: Custom database connection

text:
# Question
Title: Custom database connection
What is the best way to connect to a remote database through drupal? Would the correct method be to use the settings.php with the database in there, and use the built in db\_select, db\_query() etc functions to access the remote database?

I have a system that has a bunch of entities, which are different 'servers'. Each server may or may not have a different database for up to 4 different services. Currently, I am storing the database connection details inside of the entity fields, and calling them using entity\_load() as needed. In doing this, I am having to write my own SQL library and queries to retrieve data from the external databases.

I am wondering; if instead of writing the values to the entity fields, if I wrote them to maybe an external .php file (maybe dbconfig.php) or something, if there was a way I could still use the built in database functions and methods to access it, or if Drupal only reads from the settings.php for database connections.

I also question if using it on a table that doesn't use the same structure as drupal would even work. (It's a completely different service with it's own tables and structures).

What's the best way to handle this type of situation? I really would like to get away from writing my own library to use for remote connections, as being able to do pagination and all that using the built in methods is extremely helpful and already been tested and hardened.

Just trying to find the best way to get access to the drupal database methods/functions and still be able to update/edit/add new databases when they are needed without risking security, and without having to manually change permissions on the settings.php before making new changes. (The servers currently are automatically added as new entities by scanning a single remote db for new entries then using entity\_create() to add them).

Is it possible for me to put an include('databases.settings.php'); inside of settings.php, and use $databases\['database\_name'\]\['default'\] = $info\_array; inside of that file (and keep it writable) to store the new database values?

# Answer
You don't have to re-invent the database abstraction layer to access external databases. You can switch the database connection dynamically.

Using Database::addConnectionInfo() you can add your database connection information dynamically. Then use Database::setActiveConnection() and Database::getConnection() with your respective target database identifiers for doing your queries with.

Entity (field) queries won't work obviously, if the external database doesn't have entity tables. But static and dynamic queries will. The latter allow for including the core pagination, if desired.

After you queried your external database, use Database::setActiveConnection() without parameters to reset the connection to the defaults. This is important for Drupal to being able to access its own tables after your queries.

Check the Database API documentation and the database class for more in-depth information. (This will also work in Drupal 7 and its database class.)
> 0 votes

---
Tags: database, configuration
---


# Question
Title: Drush command to download AND enable a module
To download and install a module, I run:

```
drush dl module_name
drush en module_name -y

```

I put that in a Bash script function, and just call "drin module\_name" to simplify.

```
function drin(){
  drush dl $1
  drush en $1 -y
}

```

Is there a one-line command in Drush to download and enable a module?

# Answer
The following will download and enable the module:

```
drush en module_name -y

```

Edit: The download (dl) command is not needed. When trying to enable a module that is not downloaded yet, Drush will ask if you want to download it and then ask if you want to enable it. The -y automates the "yes" answers to these questions.

This was added in Drush 6.0.0 `(#1364814 by eiriksm, jonhattan: Added Extend pm-enable to offer downloading the project for missing extensions.)`
> 86 votes

# Answer
```
drush dl module_name && drush en module_name -y

```
> 18 votes

# Answer
Downloading and enabling a module can be done with `drush en project_name`. It asks for a confirmation; if you don't want to confirm, use the `-y` parameter.

```
drush en project_name -y

```

You can download more projects with the same command.

```
drush en rules views token -y

```

For a list of some basic Drush commands see Basics drush commands.
> 7 votes

# Answer
In Drush 9, you download a module with `composer require drupal/module_name`.

See the new documentation for Drush 9 on `drush pm:download`.

After, you will need to enable the module with `drush pm:enable module_name`.

\*Other useful commands for modules are:

* See all the modules installed

```
drush pm:list

```
* Uninstall a module

```
drush pm:uninstall module_name

```
> 1 votes

# Answer
in Drupal 8 you no longer use Drush. Use `composer require drupal/module_name` instead.
> 0 votes

---
Tags: drush
---