title: Configuration translation is not saved

text:
# Question
Title: Configuration translation is not saved
I'm working on a page where the backend needs to work in different languages.

That's why I started translating individual labels in the configuration translation (/admin/config/regional/config-translation). After I looked at the first changes, I realized that the terms were not translated.

I went back to the translation page and see that my changes have been overwritten with the original language again. So I re-translated and saved the term, which showed a success message. Then I called the translation again and it was again the value of the original language there.

Is the translation generally broken or do I have to do a specific setting?

# Answer
> 0 votes
Bug created by a module. Which enterd the system a bit to early.

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


title: Custom autocomplete form and autosubmit

text:
# Question
Title: Custom autocomplete form and autosubmit
I've added an autocomplete function for my views\_exposed\_form (a text input) using this tutorial and it works (https://www.linkedin.com/pulse/implementing-autocomplete-drupal-8-custom-callbacks-waliullah-khan).

I'd like to add a "submit on click" behaviour, so when I click on a value of the autocomplete it changes the value of the input and then submit the form.

How should I do this?

# Answer
Attaching below code:

**custom.module**

```
<?php

use Drupal\Core\Form\FormStateInterface;

function custom_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    if ($form['#id'] == "YOUR_FORM-ID") {
      $form['combine']['#autocomplete_route_name'] = 'custom.autocomplete';
      $form['#attached']['library'][] = 'custom/custom';
      $form_state->setCached(FALSE);
    }
  }
}

```

**custom.routing.yml**

```
custom.autocomplete:
  path: '/want/autocomplete'
  defaults:
    _controller: '\Drupal\custom\Controller\WantAutoController::autocomplete'
  requirements:
    _permission: 'access content'

```

**custom.libraries.yml**

```
custom:
  version: 0
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery

```

**js/custom.js**

```
(function ($) {
    Drupal.behaviors.custom = {
        attach: function (context) {
            $("#FIELD-ID").autocomplete({
                select: function (event, ui) {
                    if (ui.item) {
                        var itemLink = $(ui.item.label).attr('href');
                        window.location.href = itemLink;
                    }
                }
            });
        }
    };
}(jQuery));

```

**src/Controller/WantAutoController.php**

```
<?php

namespace Drupal\custom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Returns tree responses for nodes.
 */
class WantAutoController extends ControllerBase {

  function autocomplete(Request $request) {
    $db_conn = \Drupal::database();
    $matches = [];
    $string = $request->query->get('q');
      $alias = \Drupal::service('path.alias_manager');
      $db_conn = \Drupal::database();
      $query = $db_conn->select('node','n');
      $query->leftJoin('node_field_data', 'nfd', 'nfd.nid = n.nid');
      $query->fields('n');
      $query->fields('nfd',['title']);
      $result = $query->execute()->fetchAll();
      if ($results) {
        foreach ($results as $row) {
          $path = $alias->getAliasByPath('/node/' . $row->nid);
          $linkTonode = '<a href="' . $path . '">' . $row->title . '</a>';
          $matches[] = ['value' => $row->title, 'label' => $linkTonode];
        }
      }
    return new JsonResponse($matches);
  }

}

```

Here in the autocomplete we are building value with "a" tag. And while searching autocomplete field our autocomplete return with "a" tag also. We are also building **js** here to click on that value and redirect.
> 0 votes

---
Tags: forms
---


# Question
Title: Does ajax used in views call preprocessing hooks?
I have a view with a bunch of fields and I'm styling those fields in:

```
views-view-fields.html.twig

```

In my .theme file I'm also using a preprocess function to pass additional variables to the above template.

```
function theme_preprocess_views_view_fields(&$vars) {
  $vars['my_var'] = 'hello';
}

```

So in the twig template, I'm able to do something like:

```
{% for field in fields -%}
  {{my_var}}
{%- endfor %}

```

This is working like a charm for the first loaded fields, but when I hit "Load More" or I use exposed filters to filter down the view, the other loaded elements will not have my\_var.

Now, "kinting" my\_var directly in the template file. I saw that my\_var is NULL for all other elements loaded after with Ajax and this made me think that the problem is with **theme\_preprocess\_views\_view\_fields** being called once, the first time the page is loaded and completely being ignored from the Ajax call.

Shouldn't this preprocess be called and handled by the Ajax call Drupal is doing on the view itself?

If not, is there a way to query Drupal to re-run this hook when other elements are loaded?

Thanks!

# Answer
> 2 votes
In template "views-view-fields.html.twig" there is a three variables returned : "view", "fields", "row" you can see this here .

So to add your custom variables you need to put it into these three variables like below

```
 function dt8_preprocess_views_view_field(&$vars)
  {
    $vars['row']->my_var = 'Hey';
  }

```

and in our template "views-view-fields.html.twig" we print int like this

```
{{ row.my_var }}

```

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


# Question
Title: How does one keep a session alive across two different URLs?
I have the same drupal 7 installation running on www.mysite1.com and www.mysite2.com.

Most people redirect mysite.com to www.mysite.com, but doing so users logged in on a site aren't kept logged-in in the other site.

Since mysite1.com is running the same code as mysite2.com, I want the users to remain logged-in when switching from a site to the other one.

I assume Drupal stores the user's session ID, and when switching to the other site, the users get a new session ID, but surely there must be a way to make the two sites aware of each other, so that users are kept logged-in across two sites.

# Answer
> 0 votes
You can use Bakery Single Sign-On System module. https://www.drupal.org/project/bakery

---
Tags: 7
---


# Question
Title: hook_menu_local_tasks_alter for specific tab
I've tried with my custom module to implement hook\_menu\_local\_tasks\_alter, but I'm not sure how can I edit specific tab.

Here's my example code:

```
function my_module_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  $data['tabs']['0']['output']['0']['#access'] = FALSE;
  //krumo($data);
}

```

With this code I can hide the first tab, but that does on all pages.

When I'm using hook\_form\_alter and with krumo(form\_id) I can see what form is and I'm using switch statement to edit specific form. Is it possible to do this or something similar with tabs?

I'm not using CSS in this case, because I like to change the name of the tabs on specific pages too.

# Answer
You can use hook\_menu\_local\_tasks\_alter() in your template.php file for your theme or .module file in module like below:

```
function YOURTHEME_menu_local_tasks_alter(&$data, $router_item, $root_path) {

  foreach ($data['tabs'] as $key1 => $tabs) {
    foreach ($tabs['output'] as $key2 => $item) {

      if ($item['#link']['path'] == 'node/%/edit' || $item['#link']['path'] == 'user/%/edit') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';
      }
      else if ($item['#link']['path'] == 'node/%/delete') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';

      }
      else if ($data['tabs'][$key1]['output'][$key2]['#link']['title'] == 'View') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';

      }
      else if ($item['#link']['path'] == 'node/%/revisions') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';

      }

    }
  }
}

```

Hope this will help.
> 3 votes

---
Tags: 7, hooks, routes
---


# Question
Title: Query for email address already existing
I want to customise registration form action in my drupal8 site.I want to check email address is already existing.I have tried with different queries.But not worked.Can anyone to help me to solve this issue?

# Answer
Use this code to check if there is a user with provided email.

```
$account = user_load_by_mail($email);

if ($account) {
  // Do something.
  $form_state->setError(....
}

```

Besides, as I know in standard registration form there is already such validation.
> 0 votes

# Answer
As pointed out in the comments the email uniqueness is already checked by default.

See core/modules/user/src/Entity/User.php

```
$fields['mail'] = BaseFieldDefinition::create('email')
      ->setLabel(t('Email'))
      ->setDescription(t('The email of this user.'))
      ->setDefaultValue('')
      ->addConstraint('UserMailUnique')
      ->addConstraint('UserMailRequired')
      ->addConstraint('ProtectedUserField');

```

However, you should be able to create your own validation constraint.

First, implement hook\_entity\_bundle\_field\_info\_alter()

```
/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function mymodule_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {

  if ($entity_type->id() === 'user') {
    $fields['email']->addConstraint('MyConstraint');
  }
}

```

Then your classes

```
<?php

namespace Drupal\mymodule\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * My Constraint.
 *
 * @Constraint(
 *   id = "MyConstraint",
 *   label = @Translation("Check My Constraint"),
 * )
 */
class MyConstraint extends Constraint {

  public $message = 'My message @email';

}

```

And

```
    <?php
namespace Drupal\mymodule\Plugin\Validation\Constraint;

    use Symfony\Component\Validator\Constraint;
    use Symfony\Component\Validator\ConstraintValidator;

    /**
     * MyConstraintsValidator class.
     */
    class MyConstraintsValidator extends ConstraintValidator {

      /**
       * Checks if the passed value is valid.
       */
      public function validate($value, Constraint $constraint) {

        $this->context->addViolation($constraint->message, ['@email' => 'foo']);
      }
    }

```

I have not tested the code above but should get you most of the way there.
> 0 votes

---
Tags: users
---


# Question
Title: Nodes not get indexed after running manual cron
I'm experiencing some unexpected behavior of cron. I have used search\_api module, that should index all nodes. Automatic cron is set to 1 hour. So after every hour, cron will run automatically.

So, the issue is, I created node, and search its content, it is not searchable.

I ran cron, then searched again, still its not searchable.

After 2-3 times hitting cron manually, the content becomes searchable.

Although, for 1-2 content types, content will become searchable after hitting cron for the first time.

I have total 4 content types, and 100 nodes in my whole site.

Forcefully running cron after 3-4 times, make nodes content searchable, else my nodes are not searchable.

Is it the known issue of Drupal core or what would be the problem, I'm not able to figure out as why nodes are not getting indexed automatically? Even after cron run for Ist time, nodes not get indexed.

Any help is really appreciated.

Module used: Search\_api (version = 8.x-1.5)

Note: I can't used updated version of search\_api as of now, because my current version of Drupal is 8.3.6, and latest release of search\_api module is not compatible with this older Drupal version.

**EDIT** I have written a custom cron too, to run cron after node gets created, but this is also not solving this late cron run issue.

```
function mymodule_cron() {
  $nids = \Drupal::entityQuery('node')
    ->condition('created', array(time()-3600, time()), 'BETWEEN')
    ->execute();
  // Load all the nodes.
  $nodes = Node::loadMultiple($nids);
  foreach ($nodes as $node) {
    $node->save();
  }
}

```

# Answer
To turn off delayed indexing, navigate to the `/admin/config/search/search-api` page then click on the 'edit' button for the index.

On that page, at the very bottom, just above the Save button, there is a collapsed panel titled 'INDEX OPTIONS'. Open the panel and it should look like this.

This is where you can control whether indexing is immediate and the cron batch size.
> 0 votes

---
Tags: 8, search, cron
---


title: Breadcrumb in drupal

text:
# Question
Title: Breadcrumb in drupal
I want to breadcrumb in drupal8 that display as url as home / list page / node page. I just have in breadcrumb home \> node page.
I use bootstrap breadcrumb.

# Answer
Drupal 8 uses the page alias to build up the breadcrumb trail. Your "node page" would need to contain the "list page" alias to make it work e.g. List page = /mylist Node page = /mylist/mynode

If you want to use the menu structure then you could try this https://www.drupal.org/project/menu\_breadcrumb
> 2 votes

# Answer
You can do it with theme\_breadcrumb function. You just need to add you condition and return.In below example I am taking service node type page and list page which is created by views page and path is service.So my breadcrumb should be like this

```
Home>services>Service title

function theme_breadcrumb(&$variables){
 $path = \Drupal::service('path.current')->getPath();
 $path_args = explode('/', $path);
 $home_link = \Drupal\Core\Link::createFromRoute('Home', '<front>');
 $output = '';
if(($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']){
$typeName = $node->bundle();
if ($typeName == 'service') {
$url_object = \Drupal::service('path.validator')->getUrlIfValid('service');
$route_name = $url_object->getRouteName();
$service_link = \Drupal\Core\Link::createFromRoute('Services', $route_name);
$breadcrumb = array();
$breadcrumb[] = $home_link->toString();
$breadcrumb[] = $node->getTitle();
$output .= '<div class="breadcrumb">' . implode('<i>></i> ', $breadcrumb) . '</div>';
return $output;

   }
 }
}

```
> -1 votes

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


# Question
Title: How to add custom sort order to a taxonomy field list?
I am trying to sort the list of content according to the weight order given to taxonomy term.

**Terminology used:**

`content type` : contact-person-details

`taxonomy` : company vocabulary which has list of company names like company A, company B, ...

`session company` : every user has a company which is stored in session, users have similar company names too.

**how it works now:** Imagine I am from "company A" stored in my session. Based on my company, content in a view is getting shown (company A is the taxonomy term used for filtering). Views are used to filter the content type contact-person-details. Varies from company to company which was tagged to content, based on user session company.

**What I am trying to achieve?** Image below helps in understanding the visual concept. Imagine list (Test one, Test sort, ...) shown are the company vocabulary lists, just like (company A, company B, ...) I want an additional field or textbox just to the side of each term showing to add `weight`. This weight should be available in the view so that I'm able to making sorting based on the weight allocated for each content.

I would like to know is there a existing possibility to weight the taxonomy list in field.

If it is still complex to understand I will try to edit my explanation.

# Answer
The Taxonomy Term Reference Sortable Widget module appears to meet your requirement. Once installed, the module will provide a widget that can be selected for a taxonomy term field via its widget type panel. (Admin -\> Structure -\> Content Types -\> My Content Type -\> Manage Fields -\> My Field -\> Widget Type).

If you have a lot of different terms available this may not be a good choice because it displays a full master list of terms from which you select and order those you need. It does not have an option for using autocomplete to build the set.
> 0 votes

---
Tags: 7, views, taxonomy-terms
---


title: URL Pattern in node entity reference

text:
# Question
Title: URL Pattern in node entity reference
I have a content type A, which contains an entity reference field. That field references a content type B. I have create automatic URL paths for both content types.

When I create a new node of type A, in the same page I can add a node of type B since it's referenced. The issue is URL alias for node type B won't create. If I want that pattern for B to work I have to create that node independently (not 'inside' of node type A) or create it 'inside' A and after edit it. It will work in that case, but I'd like not to have to edit every node of type B, and just create them once and have its URL working.

I have found similar threads but nothing exactly like this. I'd appreciate any help.

Thanks!

# Answer
> 0 votes
I suppose you use D7? Do you use the Inline Entity Form module to add a new referenced node of type B? (https://www.drupal.org/project/inline\_entity\_form). I just tested the following workflow with the Inline Entity Form and Pathauto, and path aliases were successfully created for both nodes (type A and referenced type B):

* enable inline\_entity\_form and pathauto modules
* create the Entity Reference field on content type A that references content type B; select 'Inline entity form - Single value' as a widget type
* create patterns for both content types in admin/config/search/path/patterns (ex: for A - 'news/\[node:title\]'; for B - 'people/\[node:title\]')
* create a new node of type A, within it create a node of type B
* both nodes should have the correct aliases

---
Tags: entities, uri, path-aliases
---


# Question
Title: Paragraph migration for link field not working
I have below migration script for paragraph migration, where I have 2 fields, (1) icon\_type --\> List(text) field type (2) icon\_url --\> Link field type

## UPDATED WORKING CODE BELOW

If I run the migration script only icon\_type is created but not the icon\_url

```
id: icon_type_link
label: Icon Type Link
migration_group: devel
source:
 plugin: csv
 path: 'modules/custom/my_custom_module/data/icon_type_link.csv'
 keys:
   - id
 header_row_count: 1
destination:
 plugin: entity:paragraph
process:
 type:
      plugin: default_value
      default_value: icon_type_link
 uuid: uuid
 entity_id: entity_id
 icon_type: icon_type
 icon_url/uri: url
 icon_url/title: title
migration_dependencies: {}

```

# Answer
I guess both `icon_url` and `icon_type` are fields of your paragraph entity. Remove the leading blanks in front of the line

```
icon_url:

```

until it has the same indentation level as `icon_type`.

(Whitespaces are very important in YAML: Indenting something blanks makes it a child of a previous line with less blanks. In your example `icon_url` has 2 blanks and therefor it is a sub value of field `icon_type`. With only one blank \[same as `icon_type` and all the other fields\] it means that `icon_url` is a direct child of the global `process` \[the one without blanks\].)
> 0 votes

---
Tags: 8, uri, paragraphs
---


# Question
Title: Check if the site allows new user registration
In Drupal 7, on my frontpage custom template, i want to show a text if the site is allowing new users to register. Any clues? Thanks

# Answer
In a preprocess function for your template, add code something like:

```
$variables['is_registration_open'] = variable_get('user_register') == USER_REGISTER_VISITORS;

```

Then in your template:

```
<?php if ($is_registration_open) : ?>
<h3>Registration is open!</h3>
<?php endif; ?>

```
> 3 votes

---
Tags: users
---


# Question
Title: Controlling access to documents for specific users
I need customers to be able to access certain documents (PDFs mainly) specifically for them (they contain sensitive information). The document information is setup in nodes. I have looked at a lot of access control modules, but they all seem to focus on user roles. I don't want a role for every customer. What would be the best way to structure this?

# Answer
> 0 votes
A possible (but somewhat convoluted) solution could be to use Node access user reference module with private files setup. Basically adding a user reference to a node will allow them to see its content (including files) and having files' folder protected will prevent direct access to the file urls.

---
Tags: users
---


# Question
Title: How to get all the field and value of node as an array?
I am trying to render all field and value of a node as an array dynamically. How can i achieve that?

# Answer
You can use the built-in `Entity::toArray()`:

```
$node = \Drupal\node\Entity\Node::load(1);
print_r($node->toArray());

```
> 7 votes

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


# Question
Title: How do you output views reference field views in Twig?
I'm currently trying to output views referenced in a node (with Views Reference Field) inside `page.html.twig` Twig template.

I know I can just add or embed a view using `{{ drupal_view('machine_name', 'block_1') }}` (with Twig Tweak) in my Twig template. But I want the editors to have the flexibility to add or change views in the node and have them printed without writing code.

I can't seem to find any documentation on how to output a referenced view to my Twig template.

# Answer
Got it!

You have to pass the view ID and the display ID to `drupal_view()` *dynamically*.

But first let me tell you that what you are doing, printing node stuff inside page level templates, should be considered bad practice. Good practice is to leave templates untouched, and to offer field formatters and other stuff instead that keeps the admin UI intact. So, when you get your first maintenance breakdown in a year or so, don't tell us we didn't warn you.

**page.html.twig**

```
{% if node.field_views and not node.field_views.isEmpty() %}
  {% for view in node.field_views.value %}
    {{ drupal_view(view['target_id'], view['display_id']) }}
  {% endfor %}
{% endif %}

```

You won't get the view title from here. Simply add some `Global: unfiltered text` to your view `HEADER` with any title markup. That will get printed.

---

`drupal_view()` requires Twig Tweak.
> 6 votes

# Answer
> I've managed to render the view using view reference field module by printing {{ page.content }} but is there a way to explicitly to print and instead of using {{ page.content }}

At the moment you have the Views Reference Field in a content type and with `{{ page.content }}` you print the node, which is the main content of a node page.

If you want to render the View anywhere else on the page, without code, then

1. Create a custom block type: */admin/structure/block/block-content/types*
2. Add a Views Reference Field to the block type.
3. Create a custom block for this block type: */admin/structure/block/block-content*
4. Fill the reference field with a View.
5. Create a custom region: https://www.drupal.org/docs/8/theming-drupal-8/adding-regions-to-a-theme.
6. Place the block in the custom region: */admin/structure/block*
7. Print this region anyhwere in the page template: `{{ page.custom_region }}`

This is of course only necessary if content editors should be able to add or change the View. To control the permissions for block types the same way as for content types install the module Block Content Permissions. If you want to display this block only on certain node pages you can configure the block visibility.
> 2 votes

---
Tags: views, theming
---


# Question
Title: How to restrict users of other roles from seeing the site administrator details?
I have created a role called "Site Admin" and created a user with that role. When i log in with that username. "People" menu is showing in toolbar only when we give "adminster user" permissions to site admin. But when we give adminster user permission site admin can see and edit users in the site. These includes our main administrative users. How can i give permission so that site admin can only see the users excluding administrator user?

# Answer
> 3 votes
That's kind of a "asking for a module to do X" question, which is not really allowed but I do think it is a very common task.

There are a few approaches/modules to this, we are using the combination of https://www.drupal.org/project/userprotect to prevent users from editing users that already have the administrator role, and https://www.drupal.org/project/roleassign to prevent them from giving the administrator role to a user that they are allowed to edit.

There is also https://www.drupal.org/project/administerusersbyrole, which in the 8.x-2.x branch attempts to solve this without requiring users to get the administer users permission, which *is* more safe, but it also requires core patches because a lot of things in core itself can't really deal with users being able to edit other users without that permission yet.

---
Tags: 8, users, files
---


# Question
Title: How do I check the value of a Boolean field in a template file?
I have a paragraph with a boolean field.

* content type
* -paragraph entity reference
* left hand side paragraph
* checkbox
* image
* title

All the other fields have their own field-paragraph-field-checkbox.html.twig files and there's nothing to be checked, just adding a class around the image and title `{{ item.content }}` value.

However, I need to check if the checkbox field value is 1 or 0 in field-paragraph-field-checkbox.html.twig, and add a class if it's 1, or do nothing if it's 0.

When I tried printing the value with `{{ content.field_checkbox.value }}` nothing prints. I also tried with `{{ node.field_checkbox.value }}`, but I don't get any value.

How do I check the value of a Boolean field in a template file?

# Answer
> 1 votes
I don't know how you debug but I think from question contest that trying `node.field_checkbox.0.value` might work. Or if you are working with views and use `views_get_view_results` function, try `content._entity.field_checkbox.value` or `content._entity.field_checkbox.0.value` `0` used if field is untranslated

Update for comment:

```
function TEMPLATE_theme_suggestions_page_alter(&$suggestions, $variables) {

  // Check it's a node page.
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    array_splice($suggestions, count($suggestions) - 1, 0, 'page__node__' . $node->getType());
  }
}

```

with this code in your TEMPLATE.theme file drupal 8 suggest `page--node--CONTENT-TYPE-MACHINE-NAME.html.twig` (Undersores to dushes). and thats it, You might have `{{ kint(node) }}` or `{{ dump(node) }}` in your twig.

---
Tags: theming, paragraphs
---


# Question
Title: How to filter a view based for the current user based the value of custom fields in his profile and fields in the list of items viewed
I'd like to implement Views that conditionally show or hide item listings of content nodes to the current User based on:
(1) value(s) in the current User's profile and
(2) value(s) in the profile of the author of each item and
(3) value(s) in each content node itself.

A good example would be a classified ad system that enabled advertisers to specify that a given ad be shown only to users whose profiles meet a set of specific criteria.

For example: A Drupal site with User Accounts with custom fields to capture each user's age, height, and hair, and a Content Type for advertisements with the same fields.

The challenge is how to construct a View that supports a use case like the following: Users who will look at the View:
= David is a bald, 6.5 foot, 70 yr old.
= Edward is a blond, 5'5", 18 year old.
= Fred is a brown-haired, 5'11", 30 year old.
Ads that can be displayed in the View as follows:
= "Miracle Grow Hair Spray" posted by Abby to be shown only to bald people.
= "NuEar Hearing Aids" posted by Betty to be shown only to people over age 65.
= "Big and Tall Shop" posted by Carol only to be shown to people over 6 feet tall.

In summary, I'm trying to filter tablular View of nodes based on attributes of the content nodes, the authors of the node, and the current user who is looking at the View.
The standard Views filter UI supports filters based on attributes of each node in the table, but does not appear to permit any use of information about the current user other than his login state.

Any advice and references to doing the filtering at the granularity of each node would be greatly appreciated!

# Answer
I'll take the assumption that your using a content view, that way we're only making relationships to the user or user of said content.

Essentially you could add an entity reference to a taxonomy term which would in turn be referencing the piece of content to filter. So;

We create a new vocabulary, add the entity reference field. Create a new term, we'll call this 'bald'. Bald will make an entity reference to the content item 'Miracle Grow Hair Spray'.

Next we'll add a taxonomy reference field to the user profile. This will reference the users 'properies' from our new vocabulary. E.G. if our user is bald we will reference this term.

Lastly on the view we should have enough data to make a bridge to the piece of content being referenced by the term associated with said user.

Although basic & very roughly explained this should hopefully help.
> 0 votes

# Answer
This is really old, but in case anyone finds this I'll post it anyway.

You're essentially talking about personalization here. The approach you should take is to clearly define metadata to 'tag' (eg. taxonomy) your content as best as possible. Then, you'll need some way to join your content to your users. You don't necessarily need to abstract this more with add'l rules/logic - if possible you should instead try to share the taxonomy between the two, which makes it easier to query back later. Instead maybe try to think about it like this:

* I'm going to create an ad called 'Miracle Hair Grow' for bald people. I will add related tags (eg. taxonomy) of 'bald' and 'male' to my ad.
* User X is a bald male, so I'm going add the same tags to that user - I will tag them as 'bald' and 'male' (via a custom user field with entity reference to same taxonomy as above).
* Then I will build a view that will use current user as 'context' (via relationship/contextual filter). It looks like core doesn't support this in 'content' views, but in theory its pretty straightforward: show me content filtered by the current users' 'tags'. Eg. 'Show me any content tagged as 'bald' or 'male' for User X". A straightforward way to accomplish this would maybe be with views hooks. This can get pretty complicated to figure out some of the nuances, but I would start there and see if this approach would be enough. You can see how adding more variables (eg. age, hair color, etc) will become more complicated.

Is using a view definitely a requirement? Personally if I had to do this I would think it could be a lot simpler with a custom controller using view modes. You could simply get the current user, get the terms, and even pass it to a view programmatically that takes the tid's (eg 'bald', 'male') as contextual filters. You may lose out on some of the benefits of views of course and may have to handle things like ajax on your own if needed - which may not be the end of the world. Ultimately this approach would give you the most freedom and flexibility, at the cost of code maintenance.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to add custom entities to group types?
I'd like to add my custom content entity to my group types, just like the module's "group node" plugin does already with nodes bundles. Has anyone done this? There does not seem to be much progress other than the documentation request about Document making custom entity types available as content for group types.

# Answer
> 3 votes
Here's how I've solved it in the end. Although in my example I'm adding user entities, you can add whatever custom-entity you want, the approach is the same. What I needed was to add users to a group not as *members* (as already provided by the group module), but as pure user entities (group content). My answer is a basic example. See `/group/src/Plugin/GroupContentEnablerInterface.php` for a detailed description what methods etc. are available to refine the whole thing. You basically need 2 files

`module_name\src\Plugin\GroupContentEnabler\UserEntity.php`

```
<?php

namespace Drupal\module_name\Plugin\GroupContentEnabler;

use Drupal\group\Plugin\GroupContentEnablerBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a content enabler for user entities.
 *
 * @GroupContentEnabler(
 *   id = "group_entity_user",
 *   label = @Translation("User"),
 *   description = @Translation("Adds users to groups as pure entities and not as members."),
 *   entity_type_id = "user",
 *   entity_access = TRUE,
 *   pretty_path_key = "user",
 *   reference_label = @Translation("Username"),
 *   reference_description = @Translation("The name of the user (entity) to add to the group (not as a member)"),
 *   deriver = "Drupal\module_name\Plugin\GroupContentEnabler\UserEntityDeriver"
 * )
 */
class UserEntity extends GroupContentEnablerBase {

/**
 * {@inheritdoc}
 *
 */
 public function defaultConfiguration() {
   $config = parent::defaultConfiguration();
   $config['entity_cardinality'] = 1;
   return $config;
 }

 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
   $form = parent::buildConfigurationForm($form, $form_state);
   // Disable the entity cardinality field as the functionality of this module
   // relies on a cardinality of 1. We don't just hide it, though, to keep a UI
   // that's consistent with other content enabler plugins.
   $info = $this->t("This field has been disabled by the plugin to guarantee the functionality that's expected of it.");
   $form['entity_cardinality']['#disabled'] = TRUE;
   $form['entity_cardinality']['#description'] .= '<br /><em>' . $info . '</em>';

   return $form;
 }

 /**
  * {@inheritdoc}
  */
  public function calculateDependencies() {
   return ['module' => ['user']];
  }

}

```

and the second file `module_name\src\Plugin\GroupContentEnabler\UserEntityDeriver.php`

```
<?php

namespace Drupal\module_name\Plugin\GroupContentEnabler;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class UserEntityDeriver extends DeriverBase {

  /**
   * {@inheritdoc}.
   */
   public function getDerivativeDefinitions($base_plugin_definition) {
     // I used to set 'entity_bundle' to 'user' and the autocomplete for the user name never worked.
     // Checking a user with devel, the bundle is  always empty.
     // So leave it empty and specify the entity_type_id = "user" in the docblock
     // of UserEntity.php
     $this->derivatives['user'] = [
       'entity_bundle' => '',
       'label' => t('Group entity (user)'),
       'description' => t('Adds users to groups as pure entities and not as members.'),
     ] + $base_plugin_definition;
     return $this->derivatives;
    }
}

```

This can now be installed just like all the other group-content types. The `plugin_id` of this user-entity group content type is `group_entity_user:user`. Again, see the group module's source code, as the documentation is good and lot's of additional methods can be used to refine this approach.

As a warning, be very careful when creating these custom plugins as it can cause a lot of trouble when not propery configured/tested. (see my previous question)

---
Tags: 8, entities, group
---


# Question
Title: When to create schema while working with config entity?
We have a custom form `mymoduleForm.php` that is used to perform some logic by calling `mymodule_preprocess_node()`. We were able to add `addCacheableDependency()` and now the `mymodule_preprocess_node` hook is able to pull the latest changes even after making several changes and clearing cache.

We did not create a `mymodule.schema.yml` as this configuration is not used for translation or any other way then to store some value in the `some_field` field.

Although it appears to be working just fine without the `mymodule.schema.yml` file, we were wondering if it is needed. We need some guidance on whether or not this is a situation where the `mymodule.schema.yml` is needed (or if it always needed).

**mymoduleForm.php**

```
class mymoduleForm extends ConfigFormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    if (!$this->entity->isNew()) {
        \Drupal::service('renderer')->addCacheableDependency($form, $this->entity);
      }

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

    $form['some_field'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Some field title'),
      '#description' => $this->t('some description'),
      '#default_value' => $config->get('some_field'),
    ];

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

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('mymodule.settings'),
      ->set('some_field', $form_state->getValue('some_fields'))
      ->save();
  }
}

```

**mymodule\_preprocess\_node**

```
function mymodule_preprocess_node(&$variables) {
  $config = \Drupal::config('mymodule.settings');
  // add the cache tag, so that the output gets invalidated when the config is saved
  \Drupal::service('renderer')->addCacheableDependency($variables, $config);
  $config_value = $config->get('some_field');

  $library = 'mymodule/some-library';

  if($config_value == 'some_value') {
    $variables['#attached']['library'][] = $library;
  }
}

```

This is a follow up question from How to clear cache for config entity after making changes?

# Answer
Short answer: you should always have one, but you can avoid it if you *really* want (see point 3 below).

> **What are schema files used for?**
>
> 1. The primary use case schema files were introduced for is multilingual support. We need to have a tool to identify all translatable strings in your shipped configuration so when you ship with your own settings as well as default Views, additional user roles, menu items, etc. we can offer those up for translation as part of your module/theme release on http://localize.drupal.org. The nesting levels and types would be enough for this use case.
> 2. We also use schemas to provide actual translation forms for configuration based on your data. This use case is where types gain more importance and labels become crucial. The core *Configuration translation* module uses schemas to generate translation forms and save translations. The two most important built-in translatable types are 'label' for one-line text input and 'text' for multiline text input.
> 3. Using the knowledge embedded in the configuration schemas about what is stored of a configuration entity, the default persistence implementation for configuration entities **requires** a configuration schema for the configuration entity, so the right properties are exported with the types defined. Although it is better to provide configuration schemas, if you really don't want, implement the toArray() method in your configuration entity implementation to not require schema for saving configuration entities of your type.
> 4. Last but not least configuration schema is also used to automatically typecast values to their expected types. This ensures that although PHP and web forms in general favor strings over all other types, the right types are used when saving configuration. That is important so when deploying configuration, only actual changes will show up in the difference, no random type changes.

From Configuration schema/metadata
> 2 votes

---
Tags: 8, entities, hooks, configuration
---


# Question
Title: How to check whether a username already exists?
I had created a controller where I can create a new user programmitically by the following code.

```
$user = User::create();

      //Mandatory settings
      $user->setPassword($password);
      $user->enforceIsNew();
      $user->setEmail($email);

      //This username must be unique and accept only a-Z,0-9, - _ @ .
      $user->setUsername($username);

      //Optional settings
      $language = 'en';
      $user->set("init", 'email');
      $user->set("langcode", $language);
      $user->set("preferred_langcode", $language);
      $user->set("preferred_admin_langcode", $language);
      $user->activate();

      //Save user
      $user->save();
      drupal_set_message("User with uid " . $user->id() . " saved!\n");

      $uid = $user->id();

```

I am passing all variables via postman by POST method. I am using email as the username. But I want to check a condition (whether the username is already exist ) before the user creation. How can I write the if condition?

# Answer
I guess you can use a simple EntityQuery.

```
  $ids = \Drupal::entityQuery('user')
        ->condition('name', 'USERNAME_TO_CHECK')
        ->range(0, 1)
        ->execute();
    if(!empty($ids)){
      //then this name already exists
    }

```
> 11 votes

# Answer
Instead of custom one-off checks, you should use the validation API.

Before saving, call $user-\>validate(). That tells you if anything with the values isn't OK, there is also a limit on what characters are allowed for the username/email and so on.

See https://www.drupal.org/docs/8/api/entity-validation-api/entity-validation-api-overview.
> 11 votes

---
Tags: 8, users, page-controller
---


title: What argument to pass hook_update_n()?

text:
# Question
Title: What argument to pass hook_update_n()?
We have a custom module, `mymodule`, that we are using to create a custom block programmatically. We tried to do the following and it does enable the module successfully, but i get the following warning.

What is the argument that needs to be passed in?

> Missing argument 1 for mymodule\_update\_8501()

**mymodule.install**

```
function mymodule_install() {
  // Run update on install.
  mymodule_update_8501();
}

function mymodule_update_8501(&$sandbox) {
  // Do something.
}

```

# Answer
> 3 votes
A `hook_update_N` implementation is generally supposed to be invoked by the system, not manually.

Instead of thinking of it as "run an update on install", you could think of it as "perform an action on *both* install and update". A fairly common pattern for that is:

```
function MYMODULE_install() {
  _MYMODULE_install_something();
}

function MYMODULE_update_8501(&$sandbox) {
  _MYMODULE_install_something();
}

function _MYMODULE_install_something() {
  // Shared functionality here.
}

```

You don't have to use a global function; you could implement the shared functionality in a service and make use of that instead. The point is to separate out the logic for what needs to be done, and consume it in the same way wherever you need to.

If you do want to continue with your current approach, just pass it any initialised variable - doesn't matter what it is if you're not using it, and if your code is the only caller, it won't have any side-effects.

---
Tags: 8, hooks, updating, installation
---


# Question
Title: How to run the cron within specified timebound only?
I have a requirement which needs to be done via cron. Some of the jobs should run only in time frame of 9AM-7PM everyday. So how I can schedule a cron for this type of requirements in the crontab.I surfed around it, but didn't get any solutions so please anybody help me in this regard.

# Answer
To run cron you have to have something that triggers the cron since php is a scripting language and only fires off when executed. What that means is you either need an outside resources to fire off the cron or you need to set it up server side. You can set up a cron service on linux by following the guide on Drupal.org. If a scheduled cron task is not set up on the server side or some other mechanism then cron will simply run the next time a user goes to your site. This could have performance issues and unreliable cron runs.

**Custom Module**

If you don't want your cron task to run every single time cron runs then in your code you would set it up to check the current time and whether or not to run. This would require use of the date functions in php and allow you to decide whether or not to execute your code based off the time

**Elysia Cron**

Elysia cron will allow you specifically set which cron tasks run at certain times. This will require you to still set up a cron task so that cron can still fire.
> 0 votes

---
Tags: 7, cron
---


# Question
Title: Commerce 2 Add to cart with quantity field and Product Picture
I have added an image field in product variation type. Add few products to my store. Now when I am going to product detail page to add the product in cart it just shows the add to cart button without any quantity field. Also not showing Image of the product.

I tried to change the formatter to Rendered Entity, but it then only showing the picture and price but not the add to cart button. Rendered Entity was using default view mode. So I created additional view mode through manage display of product variation type but that also didn't provide any option to show the add to cart button.

What I want is to display the product variation picture + Price + SKU + Add to Cart button with quantity field.

Please guide me how to achieve this.

# Answer
> 4 votes
Please check your order item type e.g. admin/commerce/config/order-item-types/default/edit/form-display/variation\_cart\_form (default type)

Needed view mode is variation cart form. There is quantity field.

Also check this default view mode for your product variation type /admin/commerce/config/product-variation-types/default/edit/display

There is add to cart button.

# Answer
> 1 votes
The price is shown by the **purchasable\_entity** field. When you create your order item type you may (is not required) select the purchasable entity type you want your order item referred to. Typically this would be a product variation type in many cases the machine name for your product variation type matches your order item type machine name, for example if your your order item type can be **cars\_parts** then you may have **cars\_parts** product type and **cars\_parts\_variation** product variation type.

Although this setting can only be set during the order item type creation so cannot be edited afterwards, but you can edit the configuration directly in the database (not recommended) or using Drush (recommended):

```
# Drush 8
drush config-edit commerce_order.commerce_order_item_type.your_order_item
# Drush 9
drush config:edit commerce_order.commerce_order_item_type.your_order_item

```

The prior command will open your terminal fav text editor just change the line which prints **purchasableEntityType: null** to your product variation type. If that is set correctly you should check the default view display for your product variation type in */admin/commerce/config/product-variation-types/YOUR\_TYPE/edit/display*

To output this field in your *Add to cart* form mode just go to */admin/commerce/config/order-item-types/YOUR\_TYPE/edit/form-display/add\_to\_cart* and drop it in place.

---
Tags: 8, commerce
---


# Question
Title: Redirect for anonymus user doesn´t work from Controller
Community, i´ve got a simple COntroller for redirect my users by visiting a special path (localhost/drupal8/check). At the moment the redirect works for the administrator and for registrated user, if they are logged in, but not for the quests of my site (i know that it is only a local site).

```
namespace Drupal\testmodule\Controller;
use Drupal\Core\Controller\ControllerBase;

class EntityChecker extends ControllerBase {

  public function redirectToFront($bundle, $label) { return $this->redirect('<front>');

}
}

```

In the log i´m getting the following error:

> \[30-Jul-2018 09:30:25 UTC\] RuntimeException: Failed to start the session because headers have already been sent by "C:\wamp64\www\drupal8\vendor\symfony\http-foundation\Response.php" at line 1274. in C:\wamp64\www\drupal8\vendor\symfony\http-foundation\Session\Storage\NativeSessionStorage.php on line 141 #0 C:\wamp64\www\drupal8\core\lib\Drupal\Core\Session\SessionManager.php(164): Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage-\>start()

Thanks a lot for helping me

# Answer
Try this

```
<?php

namespace Drupal\testmodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RedirectResponse;

class EntityChecker extends ControllerBase {

  public function redirectToFront($bundle, $label) {
    $response = new RedirectResponse("/");
    $response->send();
  }

}

```
> 0 votes

---
Tags: 8, redirection
---


# Question
Title: How to set a url in drupal database or settings.php?
I had created a controller in custom module using drupal 8.

```
 public function subscribe(Request $request) {

        $url='https://username:password@someurl.com/v1/subscriptions';

```

}

I am using git for development. This url is actually for Razorpay subscriptions. These url might get changed according to the mode in razorpay. So the url subscriptions in razorpay for test mode and live mode is different. I have to change url every time in this custom module while managing git. Can I define this"$url" somewhere in backend in db or settings.php?

# Answer
> 2 votes
In your settings file add

```
$settings['razorpayUrl'] = 'https://example.com';

```

Then in your module

```
use Drupal\Core\Site\Settings;
$url = Settings::get('razorpayUrl');

```

---
Tags: 8, page-controller
---


# Question
Title: How do I create a view with a 'Content pane' display type?
I would like to create a new view that that I can use as a Content (panel) Pane. I cannot find how to do this. Would anyone know?

# Answer
Ok I found it.

I was looking for the option on the first screen where you give the view a name and select if it's a block or not. Instead you must add a new Display instead, on the 2nd screen, and select it from the drop down list that appears
> 0 votes

---
Tags: 7, views
---


# Question
Title: Can no longer run "composer require drupal/swiftmailer"
I have a module that relies on swiftmailer, and needs the libraries installed. Whenever I've needed to install swiftmailer libraries to a Drupal environment, I've always run this command:

```
composer require drupal/swiftmailer

```

This no longer seems to work. Running this now prompts me for authentication to git.drupal.org, and I don't understand why. Apparently this isn't the same as my drupal.org credentials:

I'm not extremely familiar with Composer and am wondering what I can do here.

# Answer
I know you're sorted now, but wanted to suggest that this could be because the repository URL for the coder module is using https.

See here:

https://help.github.com/articles/why-is-git-always-asking-for-my-password/

The link at the bottom of that article suggests that you can cache your credentials to avoid the need to enter them when using https:

https://help.github.com/articles/caching-your-github-password-in-git/

(I would have commented rather than answered, but it seems I don't have enough reputation to comment yet!)
> 1 votes

# Answer
The problem seems to be caused by the server git.drupal.org not responding. Excerpt from the posted composer output:

```
Could not resolve host: git.drupal.org; Name or service not known

```

I wonder if the reason it suddenly worked again, might be as simple as the server responding again.

The interesting part of this problem is why `drupal/coder` is installed/updated at all (when requiring `drupal/swiftmailer`) ... It's not Swiftmailer that requires Coder. **Added:** If you used "drupal-composer/drupal-project" as your starting point, Coder is required through `webflo/drupal-core-require-dev`. The question then becomes, why did Composer update Coder when you just required Swiftmailer? (That is a Composer issue.)
> 1 votes

---
Tags: 8, composer
---


# Question
Title: How do I get the field label from a node object?
I've tried guessing

```
$node->field_name->fieldDefinition->label
$node->field_name->fieldDefinition->label()

```

and

```
$node->field_name->label
$node->field_name->label()

```

but it did not work.

# Answer
Your first guess was very close, but both are protected properties, so are accessed by getters - functions with the prefix `get`:

```
$field_label = $node->field_name->getFieldDefinition()->getLabel();

```

For reference:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldItemInterface.php/interface/FieldItemInterface/8.2.x

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldDefinitionInterface.php/interface/FieldDefinitionInterface/8.2.x

**Edit:**

Btw, in twig you don't need the prefix `get`, because if you tell twig to get something with the name `label`, it tests all possibilities on the object, first it tries to access the property `label`, then the method `label()` and finally the getter `getLabel()`.

```
{{ node.field_name.fielddefinition.label }}

```
> 22 votes

# Answer
To get the field label in Twig (in this case in a node-NODETYPE.html.twig):

```
{{ content.field_FIELDNAME['#title'] }}

```
> 4 votes

---
Tags: 8
---


# Question
Title: how to change save button to Save and keep published?
In the content form want to change the publish checkbox and save button into the dropdown "**Save and keep published**" and **Save and unpublish** How can i change the layout for all content type.

# Answer
This looks like you want to change the node edit form back to the old layout of Drupal 8.3. You can use this module:

https://www.drupal.org/project/publishing\_dropbutton
> 1 votes

---
Tags: 8, nodes
---


title: Set the effective log severity level

text:
# Question
Title: Set the effective log severity level
In a Drupal 8 site, on the page `/admin/config/development/logging`, I can specify if I want warnings, errors and other messages to be displayed. But either I want them displayed or not, they exist.

On this other page, `admin/reports/dblog` , I can see all the logs available in database.

But if my site has many visitors, Debug, Info and Notice logs are constantly inserted in the database. Which causes high charge on the database and "hides" the important logs (errors and warnings).

How can I tel Drupal "Do not insert in database any log with a severity level below WARNING" ? The equivalent of the `level` value we find in every logging framework.

# Answer
> 4 votes
There is no such setting unfortunately. There is a module for 7.x, but not 8.x port yet: https://www.drupal.org/project/watchdog\_filtering.

You could use a different watchdog backend that supports filtering, or log to syslog or some other system that is better at dealing with a lot of log entries.

And if those notices/warnings are caused by PHP notices/warnings, then you should fix them.

# Answer
> 3 votes
There are a few modules for that now:

1. DBLog Filter

> DBLOG FILTER module allows you to store only filtered db log messages based on log type and log level.

2. Database Logging Conditions (Watchdog conditions)

> This module serves exactly this use case, by allowing you to enable Core's dblog module and define which log channel should be logged, and which can be dropped so that performances are maintained.

# Answer
> 0 votes
In your custom modules you can save logs dependent on the error level:

```
$error_level = \Drupal::config('system.logging')->get('error_level');
if ($error_level == 'verbose') {
  \Drupal::logger('my_custom_module')->debug($message);
}

```

---
Tags: 8, log-messages
---


# Question
Title: Entityreference not saved correctly inside ContentEntityForm
I was having a weird bug with my views. Some entity-references from my main-entity didn't show up in my view.

I investigated further with entityQuery and came across some weird action. I can get the missing referenced entities by querying for nulls in main\_entity and loading the referenced entities manually using the magic entity getter:

```
// Returns 90 main-entities. These correspond to the entities with missing data in my view.
$main_entity_ids = \Drupal::entityQuery('main_entity')
  ->notExists('field_referenced_entity')
  ->sort('created')
  ->execute();
$main_entities = \Drupal\my_module\Entity\MainEntity::loadMultiple($main_entity_ids);

// Load referenced entities for each main entity using the magic entity getter
$referenced_entities = [];
foreach($main_entities as $main_id => $main_entity){
  // Skip nulls
  if($referenced_entity = $main_entity->get('field_referenced_entity')->entity){
    $referenced_entities[$referenced_entity->id()] = $referenced_entity;

    // // Re-saving the entity here doesn't help
    // $main_entity->set('field_referenced_entity', $referenced_entity->id())
    // $main_entity->save();
  }
}

// At this point $referenced_entities -array contains 90 fully loaded refenced entities.

```

Also, the table main\_entity\__field\_referenced\_entity is missing rows for the missing references. I wonder how am I able to get the reference with the magic getter.

I tried to re-save all the entities in my loop but with no success.

The main-entity is first created and saved without the reference which is added afterwards inside ContentEntityForm::save()-method.

```
...
// Entity is saved and re-loaded
$main_entity->save();
$main_entity = \Drupal\my_module\Entity\MainEntity::load($id);
...
// Set the reference and save
$main_entity->set('field_referenced_entity', 123);
$main_entity->save();
...

```

Creating the MainEntity programmatically seems to work, inserting the required rows to the main\_entity\__field\_referenced\_entity -table:

```
$main_entity = \Drupal\my_module\Entity\MainEntity::create([
  'type' => 'main_entity',
  'status' => 1,
  'name' => 'Programmatically created MainEntity',
]);
$main_entity->save(); // No rows
$main_entity = \Drupal\my_module\Entity\MainEntity::load($main_entity->id());
$main_entity->set('field_referenced_entity', 123);
$main_entity->save(); // Row added

```

The problem seems to have started after updating to Drupal 8.5 from 8.4.4. I was running Drupal 8.5.3 when I noticed the problem. Updating to Drupal 8.5.5 doesn't help.

Does anyone have any idea what could be going on?

# Answer
Found the cause!

Someone had added the line

```
$this->getReferencedEntity();

```

to the MainEntity::\__construct()-method.

getReferencedEntity()-method uses some database-magic to find the reference and then set it to the MainEntity.

This worked fine before Drupal 8.5 but it seems that after that the system thought it already had the reference and didn't bother to insert it to the database.
> 1 votes

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


# Question
Title: Register form breaks after changing submit button value with jQuery
I need to change the submit button value (text) based on the selection made in a certain register form field. I accomplished this by using jQuery:

```
(function ($) {
$(function() {
$("#edit-field-registrierung-als-und").change(function() {
if ( this.value == "2") {
$("#registersubmit").val("Kostenpflichtig registrieren");
}
else {
$("#registersubmit").val("Jetzt registrieren");
}
});
});
}(jQuery));

```

The submit button value changes as expected. But the form is not sent anymore after submitting. The page refreshes and the entered data is still in there. I don't get any error in the console or error log. I think drupal expects the very term and is 'confused' to get a different one. Does somebody know how to resolve this?

This is my register page: https://my-business-location.com/registrierung The first field on the page influences the submit button value (option 2).

# Answer
Based on what Clive said and your response regarding the Ajax stuff, I edited your code. I am assuming you only want to change the text of the button for display purposes.

```
(function ($) {
  $(function() {

    // Create a copy of the button
    $('#registersubmit').after('<input id="new-submit" class="form-submit" value="Jetzt registrieren">');
    // Hide original
    $('#registersubmit').hide();
    // When copy  is clicked, "click" the original
    $('#new-submit').click(function(){
      $('#registersubmit').click();
    });
    // Your code with changed IDs
    $("#edit-field-registrierung-als-und").change(function() {
      if ( this.value == "2") {
        $("#new-submit").val("Kostenpflichtig registrieren");
      }
      else {
        $("#new-submit").val("Jetzt registrieren");
      }
    });
  });
}(jQuery));

```

Can't test it as you appear to have the code active right now, but it should work fine in this scenario.
> 1 votes

---
Tags: users, forms, javascript
---


title: Custom module versioning

text:
# Question
Title: Custom module versioning
I'm writing some custom modules (for a customer), but as expected their are showed in error in update dashboard (/admin/reports/updates): "No version available"

I was wondering if there's any way to tell Drupal that these module belong to another webservice to check for latest updates. So I can manage my module versioning and be aware quickly if some of my module are up to date or not.

I searched a lot about it but no result so far, if this is a duplicate feel free to point it out so I can check it out.

# Answer
> 5 votes
By default, Drupal assumes that any installed module or theme is hosted on drupal.org. This means that, if you are using a custom module (which is probably not hosted on drupal.org), Drupal will return the error you are seeing because it doesn't find any information about the module you are using, on drupal.org.

If you just want to stop Drupal from looking for a module updates, normally because you are using a different method to update it, or because the module is not hosted on drupal.org (for example, a custom module you have on your computer, on Git, Gitlab, or similar services) you can implement `hook_update_projects_alter()`.

```
function custom_module_update_projects_alter(&$projects) {
  // Hide a site-specific module from the list.
  unset($projects['custom_module']);
}

```

With this example code, the *custom\_module* module is hiding itself, but a module can hide any module. For example, if I had a *custom\_core* module that is a dependency for every custom module I use on my site, I would implement the hook using code similar to this.

```
function custom_core_update_projects_alter(&$projects) {
  // Hide all the site-specific modules from the list.
  unset($projects['custom_user_data']);
  unset($projects['custom_entities']);
  unset($projects['custom_spam_prevention']);
}

```

If you want Drupal checks for updates on a site that is not drupal.org, then the .info.yml file for the module needs to contain the following line. (See the code of the `UpdateFetcher` class, which is the class that fetches project information from remote locations.)

```
project status url: http://example.org/project-history

```

In this case, for a module using my\_module as machine name, Drupal will fetch the information about Drupal 8 releases of the module from http://example.org/project-history/my\_module/8.x.

Notice also that:

* If the .info.yml file also contains a `project: my_custom_project` line, Drupal will check for information about Drupal 8 releases of the module from http://example.org/project-history/my\_custom\_project/8.x, not http://example.org/project-history/my\_module/8.x (This is useful when a module is a sub-module of another module, and both are packaged in the same file.)
* Drupal expects that http://example.org/project-history/my\_module/8.x returns XML data that follows a specific format; you can see for example what drupal.org returns for the Date module (https://updates.drupal.org/release-history/date/8.x)

```
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
  <title>Date</title>
  <short_name>date</short_name>
  <dc:creator>vijaycs85</dc:creator>
  <type>project_module</type>
  <api_version>8.x</api_version>
  <project_status>unsupported</project_status>
  <link>https://www.drupal.org/project/date</link>
  <terms>
    <term>
      <name>Projects</name>
      <value>Modules</value>
    </term>
    <term>
      <name>Maintenance status</name>
      <value>Actively maintained</value>
    </term>
    <term>
      <name>Development status</name>
      <value>Under active development</value>
    </term>
  </terms>
  <releases>
    <release>
      <name>date 8.x-1.x-dev</name>
      <version>8.x-1.x-dev</version>
      <tag>8.x-1.x</tag>
      <version_major>1</version_major>
      <version_extra>dev</version_extra>
      <status>published</status>
      <release_link>https://www.drupal.org/project/date/releases/8.x-1.x-dev</release_link>
      <download_link>https://ftp.drupal.org/files/projects/date-8.x-1.x-dev.tar.gz</download_link>
      <date>1380568703</date>
      <mdhash>f36524e70ed83fe7f2812d3768a337c0</mdhash>
     <filesize>164918</filesize>
     <files>
       <file>
         <url>https://ftp.drupal.org/files/projects/date-8.x-1.x-dev.tar.gz</url>
         <archive_type>tar.gz</archive_type>
         <md5>f36524e70ed83fe7f2812d3768a337c0</md5>
         <size>164918</size>
         <filedate>1380568703</filedate>
       </file>
       <file>
         <url>https://ftp.drupal.org/files/projects/date-8.x-1.x-dev.zip</url>
         <archive_type>zip</archive_type>
         <md5>781eb8cb238ed8649c93f0e8e2b9e778</md5>
         <size>232819</size>
         <filedate>1380568703</filedate>
       </file>
     </files>
     <security>Dev releases are not covered by Drupal security advisories.</security>
   </release>
 </releases>

```

+ Not all the information provided is required, but for each release there must be a URL for the archive containing the module code, which is used from Drupal to download and copy the module on the site server.

As side note, updating a module files with Composer would be the first step to update the module. Drupal still needs to invoke the update hooks the module provide, and update the module information it stores in its database tables (and cache).

# Answer
> 2 votes
It's all in the docs. See Creating custom modules and then the chapter about Prepare a Module skeleton which will lead you to this example module on GitHub: https://github.com/sidharrell/D8HWexample

**hello\_world.info.yml**

```
name: Hello World Module
description: Creates a page showing "Hello World".
package: Custom
type: module
version: 1.0
core: 8.x

```

I guess you left out `version` (which is optional). Simply add it and you should get rid of the error.

---

> I was wondering if there's any way to tell Drupal that these module belong to another webservice to check for latest updates.

Well, yes, with Composer. You could start Using Composer to manage Drupal sites, most likely with this template: https://github.com/drupal-composer/drupal-project

You now can include GitHub-hosted repos pretty easily. Here comes an extremely simplified example `composer.json` that includes `MYMODULE` hosted on GitHub. The manually added type `drupal-custom-module` and the added directory take care of the rest. You may additionally add that module to your `.gitignore` now.

```
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        {
            "type": "package",
            "package": {
                "name": "MYMODULE",
                "version": "1.2.3",
                "type": "drupal-custom-module",
                "source": {
                    "url": "https://github.com/john_doe/MYMODULE.git",
                    "type": "git",
                    "reference": "tags/1.2.3"
                }
            }
        }
    ],
    "require": {
        "composer/installers": "^1.2",
        "davidbarratt/custom-installer": "^1.0@alpha",
        "drupal-composer/drupal-scaffold": "^2.2",
        "drupal/core": "~8.4",
        "drush/drush": "~9.0",
        "MYMODULE": "^1.2.3"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "alpha",
    "prefer-stable": true,
    "config": {
        "sort-packages": true,
        "bin-dir": "bin/"
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": ["load.environment.php"]
    },
    "extra": {
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/Commands/{$name}": ["type:drupal-drush"]
        },
        "custom-installer": {
            "drupal-custom-module": "web/modules/custom/{$name}"
        }
    }
}

```

---
Tags: 8
---


# Question
Title: Can an AJAX form request replace elements of different types?
I'm trying to write an AJAX form in Drupal 8. I managed to get a simple example working yesterday, but today, my work fails without error. I was wondering whether anyone here could spot my error.

Here are the relevant excerpts from my OverviewForm:

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

  ...

  $form['job_id'] = [
    '#weight' => 1,
    '#title' => 'Job',
    '#type' => 'select',
    '#options' => $formatted_jobs,
    '#ajax' => [
      'callback' => '::showFiles',
      'event' => 'change',
      'wrappper' => 'jobfiles'
    ]
  ];

  $form['jobfiles'] = [
    '#weight' => 2,
    '#title' => 'Files',
    '#type' => 'html_tag',
    '#tag' => 'span',
    '#value' => 'Please make a selection above',
    '#attributes' => [
      'id' => ['jobfiles']
    ]
  ];

  return $form;
}

public function showFiles(array &$form, FormStateInterface $form_state) {
  $job_id = $form_state->getValue('job_id');
  $elem = [
    '#weight' => 2,
    '#type' => 'item_list',
    '#items' => $this->_files($job_id),
    '#attributes' => [
      'id' => ['jobfiles']
    ]
  ];

  return $elem;
}

```

The list of jobs populates correctly, but when I select one, the initial jobfiles span isn't replaced with anything. I'd expect it to at least disappear when I select a value from the select. Thanks in advance!

# Answer
I should try using #prefix/#suffix for wrapper instead the element itself. Also IMHO it's not a good idea mess around with the elements you send during build. Take in mind the the build is done every time you render the form, even for AJAX calls. A possible solution could be hide the second element using Form States API and put the *Please make selection* in your prior element.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  // Code excerpt.
  $form['job_id'] = [
    '#weight' => 1,
    '#title' => t('Job'),
    '#type' => 'select',
    '#empty_value' => t('Please select a job'),
    '#options' => $formatted_jobs,
    '#ajax' => [
      'callback' => [get_class($this), 'showFiles'],
      'wrapper' => 'ajax-wrapper',
      'event' => 'change',
    ],
    '#required' => TRUE,
  ];

  // Render a hidden and empty list.
  $form['jobfiles'] = [
    '#weight' => 2,
    '#title' => t('Files'),
    '#type' => 'item_list',
    '#items' => [],
    '#prefix' => '<div id="ajax-wrapper">',
    '#suffix' => '</div>',
    '#attributes' => [
      'class' => ['invisible']
    ]
  ];

  return $form;
}

public function showFiles(array &$form, FormStateInterface $form_state) {
  $job_id = $form_state->getValue('job_id');
  $form['jobfiles']['#items'] = $this->_files((int)$job_id);
  // Remove the 'invisible' class.
  $form['jobfiles']['#attributes']['class'] = array_filter($form['jobfiles']['#attributes']['class'], function($v) {
    return $v != 'invisible';
  });
  // You could also return the element instead.
  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand('#ajax-wrapper', [$form['jobfiles']]));

  return $response;
}

```

Hope this may help you.

**Update**: Replace `$element` with `$form`. Also worth checking the answer provided by @joshua-moore as it is valid too.
> 1 votes

# Answer
I'm posting this answer in the hopes that it saves someone else some googling.

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

    $form['job_id'] = [
      '#weight' => 1,
      '#title' => t('Job'),
      '#type' => 'select',
      '#options' => $formatted_jobs,
      '#ajax' => [
        'callback' => '::showFiles',
        'wrapper' => 'ajax-wrapper'
      ],
      '#required' => TRUE
    ];

    $form['jobfiles'] = [
      '#weight' => 2,
      '#title' => t('Files'),
      '#theme' => 'item_list',
      '#items' => [],
      '#prefix' => '<div id="ajax-wrapper">',
      '#suffix' => '</div>'
    ];

    return $form;
  }

  public function showFiles(array &$form, FormStateInterface $form_state) {
    $job_id = $form_state->getValue('job_id');

    $elem = [
      '#title' => t('Files'),
      '#weight' => 2,
      '#theme' => 'item_list',
      '#items' => $this->_files((int)$job_id)
    ];

    $renderer = \Drupal::service('renderer');

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax-wrapper', $renderer->render($elem)));

    return $response;
  }

```

This works. Thank you, d70rr3s for your answer.
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: global webform submissions admin page per user
I have a site where users fill diferent webforms and they can visit formX/submissions to view/edit their own submissions for every particular webform. Now I need to give users something like a submissions administration page, where they can have a global view of their submissions to all webforms and be able to edit which one they choose. is it possible to build this global submissions page with webform?

# Answer
You literally read my mind because I just added this feature to latest dev release of the Webform module for Drupal 8

@see Users can view all their submissions across all webform instances.
> 2 votes

---
Tags: webforms
---


title: Renaming the name of a field in a View

text:
# Question
Title: Renaming the name of a field in a View
I've set up a View which displays the latest posts of a custom content type. Its fields are the usual, such as image, summary and title.

Though I would like the name of title that the View displays to be different than the original.

So for example the name of the title in the content type is **Location of Project**. Rather, I would like to have the View title only display **Location**. The titles' output would continue to show the same information, for example **Canada**.

Couldn't find a way to achieve this using the Views config. Any help would be appreciated.

# Answer
> 1 votes
There is an option in Field configuration to **Create a label**. It's usually just at the top of the options.

You have to tick it to enable it. Once you tick it an input field appears where you can enter a different label for your field.

To get to the field configuration just click on the desired field under `Fields` area in your Views.

---
Tags: views
---


# Question
Title: How to test for a boolean field in a twig template?
`field_boolean` is a boolean field.

`{% if content.field_boolean == true %}` or `{% if content.field_boolean == 1 %}` or `{% if content.field_boolean == 'true' %}` or `{% if content.field_boolean == '1' %}` don't work.

How do I test if the checkbox is checked?

# Answer
You want to look at the raw value, not the render array.

Example:

`{% if node.field_foo is not empty %}`

This checks if the field exists. The render array won't be useful beyond rendering values.

Don't look at `content` \- that is simply the render array. Look at the fields in your entity object (node, paragraph, etc). You might want to install Twig XDebug to breakpoint your templates or inspect variables in `mytheme.theme`.

You *should* be able to look at `{% if node.field_foo.value ... %}` for equality checking.
> 14 votes

# Answer
Here is how I solved this, it requires the twig\_field\_value project.

For the boolean field, set the on and off values to 1 and 0 respectively.

In twig:

`{% if content.field_foo|field_raw('value')|number_format(0,'.',',') is same as('0') %}
 the box is NOT checked
{% endif %}`
> 1 votes

# Answer
This works for me.  `{% if '1' in content.field_name.0 %}
 {{ "anything" }}
 {% endif %}`

Source
> 1 votes

---
Tags: theming, 8, entities
---


title: Handling the 'default/' folder in Git

text:
# Question
Title: Handling the 'default/' folder in Git
I am running a legacy project with four developers on it. Occasionally I need to make changes to settings.php for remote server settings and/or a settings override example template in this directory. It seems like any time cache is cleared, the default folder permission is changed to not be writable, and the settings file changed to 644. Which I get.

However, the next time someone does a `git pull` and there are changes in that file, git says it does not have permission to touch it and the pull fails.

Is there any strategy to handling this? I tried searching but came up short.

Edit: this may sound like a Git question at a glance, but it’s due to how Drupal changes certain directories to be read only and not writeable which causes issues when those files update and are pushed to a repo for others. Therefore there must be some strategy to handle this.

# Answer
The answer from @leymannx stops git from recognizing and pushing file permission changes to the repository.

Yet, it doesn't stop Drupal from denying write access to the configuration files after your cache cleared, and thus a git pull to fail if it can't write changes to these files.

As the permissions set automatically by Drupal still allow write access for the file owner, the easiest solution would be running `git pull` with the same user that is running the local webserver.

If that is no option, your developers may try to use access control lists (`setfacl`) for advanced write permissions to their local sites folders on Linux systems.

Another option would be to wrap the git executable with a custom shell script in their local binary paths, that ensures proper write permissions (unfortunately there's no pre-pull git hook).

As a last resort, you can patch the core. There is lots of discussion of whether and how to allow developers to circumvent file protection for setting files. None of the proposed solutions made it to core yet. But the patch from this issue for Drupal 7 allows a custom setting in your local development environment settings (e.g. in `settings.local.php`) to disable file permission changes.
> 2 votes

# Answer
Configure Git to ignore file mode changes:

```
$ cd repo
$ git config core.fileMode false

```

Source: How do I make Git ignore file mode (chmod) changes? (Bookmark this!)

---

Additionally, ensure that your whole project including its `.git/` directory is owned by the same user and group. You maybe were logged in as `root` or a different user the last time you `git pull`ed and by that accidentally mixed up file ownership.

```
$ ls
foo bar repo
$ sudo chown -R user:group repo/

```

`group` most likely is `www-data`.
> 1 votes

---
Tags: 7
---


# Question
Title: How to set up permissions for the private files directory?
I'm trying to set up the private files directory and I'm getting the following error.

> The backup file could not be saved to 'private://backup\_migrate/' because the directory could not be created or cannot be written to. Please make sure your private files directory is writable by the web server.

Could someone help correct my misstep? I've scoured scads of pages of documentation, and oddly I don't seem to be able to find a reliable path to a solution. Lots of conflicting info and lots of missing details.

Here's my setup:

1. bitnami drupal image (centos)
2. path to Drupal /root/apps/drupal/htdocs
3. I've connected as root via ssh

Here are the exact steps I've followed, and which best reflect my understanding so far of what I should do:

1. `# cd /root/apps/drupal/` to go to directory that contains the web root directory
2. `# mkdir private-files`
3. `# drush dl file_permissions --destination=~/.drush` to download the contributed file\_permissions utility, which says it handles all necessary permissions changes
4. `# nano sites/default/settings.php` to tell Drupal where to find the directory, set `$settings['file_private_path'] = '/root/apps/drupal/private-files';`
5. `# drush cr` to clear Drupal and Drush caches
6. `# drush fp` to run the file\_permissions utility; it responds:

> Your httpd user: daemon \[status\]
> Your httpd group: daemon \[status\]
> You will be prompted for admin password to be able to change \[warning\]
> permissions with `sudo` command.
> Security warning: Couldn't write .htaccess file. Please create a \[error\]
> .htaccess file inyour private:// directory which contains the
> following lines: \<pre\>\<code\># Deny all requests from Apache 2.4+.
> \<IfModule mod\_authz\_core.c\>
> Require all denied
> \</IfModule\>
>
> \# Deny all requests from Apache 2.0-2.2.
> \<IfModule !mod\_authz\_core.c\>
> Deny from all
> \</IfModule\>
> \# Turn off all options we don't need.
> Options -Indexes -ExecCGI -Includes -MultiViews
>
> \# Set the catch-all handler to prevent scripts from being executed.
> SetHandler Drupal\_Security\_Do\_Not\_Remove\_See\_SA\_2006\_006
> \<Files\*\>
> \# Override the handler again if we're run later in the evaluation list.
> SetHandler Drupal\_Security\_Do\_Not\_Remove\_See\_SA\_2013\_003
> \</Files\>
> \# If we know how to do it safely, disable the PHP engine entirely.
> \<IfModule mod\_php5.c\>
> php\_flag engine off
> \</IfModule\>\</code\>\</pre\>
7. `# drush cr` to clear Drupal and Drush caches
8. `# ls -al` to see permissions; it shows:

> total 8628
> drwxr-xr-x 7 root root 134 Jul 23 12:04 .
> drwxr-xr-x 5 root root 53 Jun 7 13:52 ..
> lrwxrwxrwx 1 root root 14 Jun 7 13:55 .bitnamimeta -\> ../../var/meta
> -r-xr--r-- 1 root root 8826689 Jun 7 13:31 bnconfig
> drwxr-xr-x 4 root root 146 Jun 7 13:51 conf
> drwxr-xr-x 12 root root 4096 Jun 7 13:51 drush
> drwxr-x--- 9 root daemon 4096 Jul 18 13:46 htdocs
> drwxr-xr-x 2 root root 25 Jun 7 13:51 licenses
> drwxrwsr-x 2 daemon daemon 23 Jul 23 13:45 private-files
> lrwxrwxrwx 1 root root 33 Jun 7 13:54 updateip -\> /opt/bitnami/apps/drupal/bnconfig
9. `# ls -al private-files/` to see permissions; it shows:

> total 4
> drwxrwsr-x 2 daemon daemon 23 Jul 23 13:45 .
> drwxr-xr-x 7 root root 134 Jul 23 12:04 ..
> -rw-r--r-- 1 root daemon 687 Jul 23 13:47 .htaccess

Needless to say, pretty frustrating since I've spent at least 4 hrs on what I imagine must be simple for someone already familiar with all the components.

Since I am new to servers as well as to Drupal, please break out actual steps vs merely invoking (vague-to-me) concepts such as 'change user group' or the like.

# Answer
> 3 votes
Your Drupal folder is owned by `daemon:daemon` and your private files directory is owned by `root:root`.

Fix it by making your private files directory at least owned by the same group:

`$ chown -R daemon:daemon /root/apps/drupal/private-files`

---

Sorry, I reread your `ls -la` output again, this time on a bigger screen, and it seems to be the other way around. Your private files folder is already owned by `daemon:daemon` where in this setup it should be `root:root` instead:

`$ chown -R root:root /root/apps/drupal/private-files`

---

After reading through this thread from 2013 https://community.bitnami.com/t/how-in-bitnami-cloud-drupal-set-up-a-secure-private-file-system-path-folder/9652 it seems your files and folders ownership got messed. Seems that all your Drupal including private files should indeed recursively be owned by `daemon:daemon`. Generally, logging in as `root` should be avoided.

# Answer
> 1 votes
I would not create the folder as root, let the site create its own folder. Just set the path in your settings.php and then go to 'File system' in the Drupal site (configuration). You can see your path reflected here. Then just save the form and Drupal will create the folders with right permissions.

# Answer
> 1 votes
Your configuration looks like this:

```
Your httpd user: daemon [status]
Your httpd group: daemon [status]

# ls -al /root/apps/drupal/private-files
total 4
drwxrwsr-x 2 daemon daemon 23 Jul 23 13:45 .
drwxr-xr-x 7 root root 134 Jul 23 12:04 ..
-rw-r--r-- 1 root daemon 687 Jul 23 13:47 .htaccess

```

On a *vanilla* \*nix system, that is *all* it takes to give `daemon` full access to the `private-files` directory. I.e. when the Drupal **Backup and Migrate** tries to create `'private://backup_migrate/` it *should* be allowed to to so. As indicated by the error message you've posted, it is *not*.

Finding: You're *not* running a vanilla \*nix system.
So what can be wrong?

There is no way of knowing without knowing a lot more about your server configuration, but given that you're running *CentOS*, I suspect that you're having an issue with something known as "*SELinux*". Btw. *SELinux* is great! But it imposes an extra layer of security that sometimes comes as an surprise to the uninitiated.

Basically, if *SELinux* is in use, to fix permissions – in addition to the mod-bits – you *also* you need to make sure that the *security* policy for your `private-files` directory allows `daemon` to create subdirectories there.

First navigate to the the Drupal configuration directory (`sites/default`) and inspect the security context label for the public file upload directory:

```
$ ls -Z .
drwxrwxr x. daemon daemon unconfined_u:object_r:httpd_sys_rw_content_t:s0 files

```

The label here is `httpd_sys_rw_content_t`.

Then make sure that `private-files`is tagged with the *same* label. Navigate to `/root/apps/drupal` and a give command similar to this (use the label used on *your* configuration):

```
$ sudo chcon -R -t httpd_sys_rw_content_t private-files

```

(Source: http://heim.ifi.uio.no/gisle/staging2/drupalprimer/drupal/cf\_files.html#f\_selinux)

---
Tags: 8, security, files
---


title: How critical is SA-CORE-2018-005?

text:
# Question
Title: How critical is SA-CORE-2018-005?
The Security advisories does not mention the usual classification for how critical this is (probably because it is about 3rd-party libraries). Can the whole site be compromised with this vulnerability or is it about accessing restricted content?

Ref.

https://www.drupal.org/SA-CORE-2018-005

https://symfony.com/blog/cve-2018-14773-remove-support-for-legacy-and-risky-http-headers

# Answer
> 12 votes
The specific vulnerability seems to be the ability of a requester to send one request path to the webserver, but use an HTTP header to make Drupal see a different path.

The rewrite happens early, so the access layer in Drupal/Symfony runs as intended. But it bypasses path-based restrictions that happen earlier ("on higher level caches and web servers", according to the CVE at https://symfony.com/blog/cve-2018-14773-remove-support-for-legacy-and-risky-http-headers).

For example, if you use .htaccess to restrict `/admin/*` from outside your IP range, that might be bypassed, but Drupal's own access system will still work as it should.

# Answer
> 2 votes
At https://www.cybersecurity-help.cz/vdb/SB2018080118?affChecked=1 this vulnerability is described as low-risk. I haven't been able to find anything that describes in any detail how it can be exploited, though.

---
Tags: 8, security
---


title: Update issue of Drupal 8.34

text:
# Question
Title: Update issue of Drupal 8.34
Currently, there is a security issue of Drupal CMS, I'm using Drupal version 8.3.4, does the version 8.3.9 can solve the security issue released on March 28th, 2018 PSA-2018-001 (core highly critical release)?

I tried to update to version 8.5.5, but some of the modules did not work after an update. I got the error message "the website encountered an unexpected error. please try again later".

# Answer
> 2 votes
As you can read on https://www.drupal.org/project/drupal/releases/8.3.9 Drupal 8.3.9 fixes SA-CORE-2018-002 (and hence probably also SA-CORE-2018-001). However, there has been several later issues - see https://www.drupal.org/security \- and only Drupal 8.5 is supported. Quote from the latest 8.5.6 release:

> Versions of Drupal 8 prior to 8.5.x are end-of-life and do not receive security coverage

In other words, you better upgrade to Drupal 8.5.6 and fix/upgrade the modules that no longer works.

---
Tags: security
---


# Question
Title: How to do a RedirectResponse with a destination query parameter?
This works:

```
$redirectURL = '/cart/add/p2';
return new RedirectResponse(base_path().$redirectURL);

```

The problem is, I want this:

```
$redirectURL = '/cart/add/p2?destination=somewhere';

```

The moment I added destination=somewhere, I get this error:

```
InvalidArgumentException: The internal path component 'http://localhost/XXXX/public_html/XXXX/XXXX' is invalid. Its path component must have a leading slash, e.g. internal:/foo. in Drupal\Core\Url::fromInternalUri() (line 404 of C:\ampps\www\XXXX\public_html\core\lib\Drupal\Core\Url.php).

```

However, if I do this:

```
$redirectURL = '/cart/add/p2?SOMETHING_ELSE=somewhere';

```

Then it works. In other words, it specifically breaks if I add "destination=somewhere".

Why would it be breaking on this and how do I get around it? I.e. How do I redirect to a URL with destination=somewhere in the query string.

FYI: If I can get this to work, I can use "Cart Links" to add stuff to a cart and redirect the user at the same time, making my live a lot easier.

# Answer
Better use a route, so that the path processing in Drupal can do its job. If `custom.cart_add` is the route to `/cart/add/{page}`, this returns a redirect response with a destination query parameter from a controller:

```
  return $this->redirect(
    'custom.cart_add',
    ['page' => 'p2'],
    [
      'query' => ['destination' => 'somewhere'],
      'absolute' => TRUE,
    ]
  );

```
> 8 votes

# Answer
Try this code.

```

$path = Drupal\Core\URL::fromUserInput('/cart/add/p2', array('query' => array('SOMETHING_ELSE' => 'somewhere')))->toString();
$response = new RedirectResponse($path);
$response->send();

```
> 7 votes

# Answer
This full example might help:

```
use Symfony\Component\HttpFoundation\RedirectResponse;

$target = 65; // a parameter you want to add
$url = Url::fromUri('internal:/node/add/page'); // choose a path
$link_options = array(
  'attributes' => array(
     'class' => array(
        'btn',
     ),
   ),
   'query' => array(
     'target' => $target
   )
);
$url->setOptions($link_options);
$destination = $url->toString();

$response = new RedirectResponse($destination);
$response->send();

```
> 5 votes

# Answer
```
$redirectURL = '/cart/add/p2';
return new RedirectResponse(base_path().$redirectURL);

```

The code above produces double slash before the *cart* item, because `base_path()` always adds a slash at the end of the returned path. You need to remove the slash from `$redirectURL` variable to get it work correctly.
> 3 votes

---
Tags: 8, redirection
---


# Question
Title: Kernel base test for media view displays is failing with: LogicException: Missing bundle entity, entity type media_type, entity id image
I am trying to test media view displays via a test, which is based on the KernelTestBase class. I have also tried to inherit from Drupal\Tests\media\Kernel\MediaKernelTestBase, but got the same error from bellow:

> LogicException: Missing bundle entity, entity type media\_type, entity id image.

My test class looks like this:

```
<?php

namespace Drupal\Tests\degov_image_and_crop_styles\Kernel;

use Drupal\Core\Extension\ModuleHandler;
use Drupal\KernelTests\KernelTestBase;

class ModuleInstallationTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = [
    'user',
    'migrate',
    'migrate_drupal',
    'system',
    'node',
    'taxonomy',
    'field',
    'file',
    'image',
    'media',
    'media_test_source',
    'text',
    'filter',
    'language',
    'content_translation',
    'image_widget_crop',
    'crop',
    'lightning_core',
    'responsive_image',
    'breakpoint',
    'degov_image_and_crop_styles',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->installEntitySchema('node');
    $this->installEntitySchema('file');
    $this->installEntitySchema('media');
    $this->installEntitySchema('taxonomy_term');
    $this->installEntitySchema('taxonomy_vocabulary');
    $this->installEntitySchema('user');
    $this->installSchema('system', ['sequences']);
    $this->installSchema('user', 'users_data');
    $this->installSchema('file', 'file_usage');
    $this->installSchema('node', ['node_access']);
    $this->installConfig(self::$modules);
  }

  public function testSetup(): void {
    /**
     * @var ModuleHandler $moduleHandler
     */
    $moduleHandler = \Drupal::service('module_handler');
    self::assertTrue($moduleHandler->moduleExists('degov_image_and_crop_styles'));
    self::assertTrue($moduleHandler->getModule('degov_image_and_crop_styles'));
  }

}

```

Does anyone know, what I am missing here?

# Answer
I could solve this via:

`$this->createMediaType('image');`

Also I inherited from MediaKernelTestBase.
> 0 votes

---
Tags: 8, testing
---


# Question
Title: Drush > ignore files and folders (ie : IDE conf) when pm-update
Do you know if is there a way (by command argument, or in config) to ask drush not to remove IDE's configuration files and folder?

To be clear, Phpstorm create a .idea folder with project configuration in the root folder; when I run `drush pm-update drupal`, this folder is removed. Is there a way to ask drush to not delete this folder?

# Answer
> 3 votes
Nope. Drush always does a full directory replacement when upgrading a module with pm-update. This insures that any files removed from the release do not remain on the disk after the update. Contributions to improve drush in this area would be appreciated.

As a workaround, if you have your .idea folder checked into git, then you could always use `git checkout -- .idea` after pm-update to get it back.

# Answer
> 0 votes
The same thing happened to me, then I remembered that drush restores the directory **sites**, so you could locate all your permanent files inside that folder. Another option is to recover them from the backup drush does when updating...

I hope this helps

---
Tags: drush
---


title: Copy url in link to webform

text:
# Question
Title: Copy url in link to webform
I would like to know if it is possible to set up a link on a node to open a webform and copy the url from the node where the link sits to a field in the webform when it opens. If not, maybe copy some text in the link to the webform?

# Answer
> 0 votes
It turns out that it needed **%get\[product\_url\]** instead of **\[current-page:query:product\_url\]** in the webform field. It is now working.

# Answer
> 0 votes
Probably the easiest way to do it would be to pass the path in a GET variable and use a token.

So on your node page edit the webform link to include the path like so

```
<a href="/link/to/webform?yoururl=theurlyoureon">Webform link</a>

```

Then on your webform for that textfield use \[current-page:query:yoururl\] as your default value.

Obviously replace yoururl with whatever you want to name the variable.

---
Tags: hooks
---