# Question
Title: How can I query on a custom content entity base fields?
I am trying to write a entityQuery and add condition on the base fields I've defined.

The query:

```
$query = \Drupal::entityQuery('map_object')
    ->condition('body', 'Test')->execute();

```

And the error:

```
Drupal\Core\Entity\Query\QueryException: 'body' not found in Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable() (line 316 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).

```

The definition:

```
    $fields['body'] = BaseFieldDefinition::create('text_long')
      ->setLabel(t('Body'))
      ->setDescription(t(''))
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'text_textfield',
        'weight' => 9,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

```

The column "body" does exists in the entities base table.

# Answer
> 1 votes
I was missing `data_table` in the Entity annotation. By adding that and update the entity it allowed me to query as expected.

```
 *   base_table = "map_object",
 *   data_table = "map_object_field_data",

```

---
Tags: 8
---


# Question
Title: How can I import/rewrite settings/content types/blocks/etc from live with the newly developed features on dev?
I have a site that's already up and running. On my local dev environment I occasionally develop new features for that site.

I have certain configs(blocks, settings, etc) that I need to add to the live site. However, I can't seem to figure out a way to import them without deleting the current blocks/settings/etc that already exist on the live site.

Is there some way that I could import them on the live site without deleting them beforehand?

# Answer
IMHO, using git for that works quite well.

You have a production branch and a development branch (and possibly many feature branches). Locally, you are on the develop branch, you make your changes there, export and commit your changes there

Before you do a deployment, you switch to production branch, do a config export ,sync it down, commit it, merge develop into production, do a local config import to make sure that things are consistent and then deploy.

A useful presentation for this is https://de.slideshare.net/nuvoleweb/advanced-configuration-management-with-config-split-et-al, for example slide 39, although that focuses more on working with multiple developers, but the process with production is similar.
> 1 votes

---
Tags: 8
---


# Question
Title: Form submission in modal is throwing an error
I have a Form which on submit calls another form via ajax and embeds it into a modal popup (Drupal8 standard) and when I click on submit of that modal form , I get a Drupal ajax error (I think it's due to the fact that ajax tries to find the from on the wrong page).

Here is how the submit button of the first form looks:

```
$form['table'][$pid]['edit'][$cid] = [
      '#type' => 'submit',
      '#id' => 'edit_'.$cid,
      '#name' => 'edit_'.$cid,
      '#value' => $this->t('Edit'),
      '#ajax' => [
        'callback' => [$this, 'customAjaxModalForm'],
        'event' => 'click',
      ],
  ];

```

And here's the `customAjaxModalForm` method, which calls the other form and modal.

```
public function customAjaxModalForm(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $modal_form = \Drupal::formBuilder()->getForm('\Drupal\accounts\Form\ContactsForm');
  $response->addCommand(new OpenModalDialogCommand('Edit contact', $modal_form, ['width' => '800', 'height' => '300']));
  return $response;

```

}

Now the submit of the `ContactsForm` looks exactly as the submit above, as I need to send a few responses to the client (.js).

The rest of the code is pretty straight forward so I only supplied the most crucial parts.

How my code works, is: you go to a page, controller handles the request, it calls the first form (the form only has a textfield and three submit buttons, the other two submit buttons work - do their job) the rest you know.

Any ideas? I am at a loss.

# Answer
> 0 votes
Ok, after a a few hours tinkering and extensive googling, i sadly found the answer i was looking for (but not hoping for).

How to open a popup form from a view link?

Turns out, in D8 this is impossible.

# Answer
> 0 votes
i was also faced the same problem . drupal 8 examples shows only the popup when user clicks the link instead of form submission .so changed the popup as alert in javascript for my scenario

---
Tags: forms, ajax
---


title: Create User Picture Field

text:
# Question
Title: Create User Picture Field
I accidantly deleted the user picture field while development. Now the app is production and a new feature should provide user pictures.

How do I get back the user picture field?

# Answer
You'll find the configuration files of the user picture field in the standard profile. You can export the complete config, add the yaml files of the field and reimport again.

Or if you want to import the field in UI, go to *admin/config/development/configuration/single/import*, select the configuration type **Field storage** and import the content of

`core/profiles/standard/config/install/field.storage.user.user_picture.yml`

The same for the configuration type **Field** and the content of

`core/profiles/standard/config/install/field.field.user.user.user_picture.yml`.
> 2 votes

---
Tags: 8
---


# Question
Title: Display value not key of list after loading of node
I've created a controller and I'm loading a node.

```
$variables['contest'] = Node::load(12);

return [
    '#theme' => 'theme_contest',
    '#variables' => $variables,
];

```

In this node there is a field "field\_contest\_things" of type list (text):

```
0|Dance
1|Read
2|Playing

```

In the twig file if I'm doing

```
{{ variables['contest'].field_contest_things.value }}

```

this will display the key and not the "value".

Is there any way that I can display the value and not the key in the twig ? Or should I change something in my controller ?

Thanks

# Answer
If your field allows only 1 value, you can do it in both ways, i.e Controller or Twig :

**Controller**

```
$node->field_contest_things->getFieldDefinition()->getSetting('allowed_values')[$node>field_contest_things->value];

```

**Twig**

```
{{ node.field_contest_things.fieldDefinition.settings['allowed_values'][node.field_contest_things.value] }}

```

*Update*

You can now skip the usage of `fieldDefinition` on the latests Drupal 8 updates:

```
{{ node.field_contest_things.setting('allowed_values')[node.field_contest_things.value] }}

```

---

By experience, I suggest you to move for a taxonomy if you need to query your node by this field value on the future. It's more maintainable & scalable.

---

Hope it helps you !
> 5 votes

---
Tags: theming
---


# Question
Title: How to force D8 "Configuration synchronization" to send HTTPS download URL
I have a Drupal 8 site hosted on an Apache Server. There are 2 virtuals hosts :

* one listening on port 80, which redirects everything to HTTPS
* one listening on port 443 which serves the htdocs directory where the Drupal site is located

Everything works well, except for the "Configuration synchronization" full export. When I click the "Export" button, I'm redirected to the home page, without any message or log.

Enabling the console on my web browser, I saw these calls :

```
POST https://my.domain.fr/admin/config/development/configuration/full/export
[HTTP/1.1 303 See Other 86 ms]
GET http://my.domain.fr/admin/config/development/configuration/full/export-download
[HTTP/1.1 301 Moved Permanently 101 ms]
GET https://my.domain.fr/
[HTTP/1.1 200 OK 183 ms]

```

The download process of the config file seems to be *killed* by the redirection.

The second URL (GET http) is sent by Drupal in the response to the first call, in the "Location" header.

How can I force Drupal to send only HTTPS url, even in the Location header in this precise case ?

**Edit:** Potentially linked post

**Edit2:** I'm having the same trouble with the **RSS link** on the site : on the page returned by `https://my.domain.fr`, the RSS link is `http://my.domain.fr/rss.xml`

**Edit3:** Found the solution for the export problem (see answer below). Still not a solution for the RSS link, but it's not the main subject of this post.

# Answer
> 0 votes
I forgot the `SSLEngine On` Apache directive in the configuration of the VHost listening on port 443.

With it, the Location header sent by Drupal contains now `https` scheme.

---
Tags: 8, redirection, configuration
---


# Question
Title: How to use unique taxonomy term for nodes in Drupal 7?
I have unique categories assigned to nodes via taxonomy module. now I want the path to be something like this:

```
root/taxonomy-vocabulary/taxonomy-term/node-titel

```

Any ideas?

This question has already been asked for Drupal 8 but I am running Drupal 7. So there might be a module or setting for this?

# Answer
You can install Pathauto module and set template for your node's path as you want on page admin/config/search/path/patterns

In this case You can use all this tokens with taxonomy term names, something like that: \[node:taxonomy-vocabulary-1:name\] etc. List with all this tokens is on admin/config/search/path/patterns page
> 1 votes

---
Tags: path-aliases, taxonomy-terms
---


title: What is the use of sync directory?

text:
# Question
Title: What is the use of sync directory?
I see in Drupal documentation about Configuration Management it is adviced to change the location of the `sync` directory in a production environnement.

But I can't find an explanation about the **actual use of this directory**. For what does Drupal use it ? (I expect a more accurate answer than "synchronizing", which I can formulate myself but is not very helping...)

And why is it unadvised to keep this directory accessible from the web ? What could be the consequences ?

# Answer
> 4 votes
It's where Drupal exports configuration (YAML files) to, and reads configuration from (for example using `drush config-export` and `drush config-import` respectively). The term "synchronising" refers to Drupal comparing the contents of those files to the site's active configuration, and applying any config that's changed.

You want to keep that folder out of the public web server for at least 2 reasons:

1. Those files could potentially contain sensitive data
2. You're potentially exposing the structure and configuration of your site to the world. Those details could be advantageous to an attacker.

Best to err on the side of caution and keep them away from prying eyes.

---
Tags: 8, configuration
---


# Question
Title: Front page returns 403 for unauthorized users
I'm trying to get a D7 staging site's git repo up-to-date with its production server repo. In other words, I changed A LOT of stuff on staging (by running `git fetch <branch> && git reset --hard`). Now the site is up-t-date and works perfectly, except for one thing: to front page returns a 403 error for unauthenticated users.

My assumption is the error is in the `.htaccess` file. I did not overwrite it with the merge, though. Luckily I'm useless when it comes to handling `.htaccess`, and now have the opportunity to ask the smart folks on drupal stackexchange for their guidance.

The `.htaccess` file:

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

# Add headers to all responses.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
</IfModule>

```

# Answer
> 0 votes
I'm sure there are a ton of reasons why this could happen, but in this particular case, the front page just needed to be explicitly saved and published. I can't say why this is, I had not made any other content edits on the site, but if anyone runs into this issue try saving the page in question!

---
Tags: 7, .htaccess
---


title: Embed autocomplete textfield in a block

text:
# Question
Title: Embed autocomplete textfield in a block
I'm using the following code to embed an autocomplete field in a block. However the autocomplete process does not execute when I type in input:

```
function cse_block_info(){
    $blocks = array();
    $blocks['cse_search'] = array(
        'info' => t('CSE Search'),
    );

    return $blocks;
}

function cse_block_view($delta=''){
    switch ($delta) {
        case 'cse_search':
            // The subject is displayed at the top of the block. Note that it
              // should be passed through t() for translation. The title configured
              // for the block using Drupal UI supercedes this one.
              $block['subject'] = t('Title CSE block');
              // The content of the block is typically generated by calling a custom
              // function.
              $block['content'] = cse_block_content($delta);
            return $block;

        break;

        default:
        break;
    }

}

function cse_block_content($which_block){
    switch ($which_block) {
        case 'cse_search':
            $form['cse_search'] = array(
                '#title' => t('CSE Autocomplete TEST!'),
                '#type' => 'textfield',
                '#autocomplete_path' => 'cse/google/autocomplete',
            );

            // Adds a simple submit button that refreshes the form and clears its
            // contents. This is the default behavior for forms.
            $form['submit'] = array(
                '#type' => 'submit',
                '#value' => 'Save',
            );

            return $form;
        break;

        default:
        break;
    }
}

```

I implement the same code as a stand alone system i:e not placed inside a block and the process works flawlessly.

**Can anyone help with suggestions of why my attempt to place an autocomplete in a block does not work?**

# Answer
> 0 votes
Your block content should look like this:

```
function cse_block_content($which_block){
  switch ($which_block) {
    case 'cse_search':
      drupal_render(drupal_get_form('my_custom_form'));
    break;

    default:
    break;
  }
}

function my_custom_form($form, &$form_state) {
  $form['cse_search'] = array(
      '#title' => t('CSE Autocomplete TEST!'),
      '#type' => 'textfield',
      '#autocomplete_path' => 'cse/google/autocomplete',
  );

  // Adds a simple submit button that refreshes the form and clears its
  // contents. This is the default behavior for forms.
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Save',
  );

  return $form;
}

```

---
Tags: 7, blocks
---


title: Drupal 8 View - get url field

text:
# Question
Title: Drupal 8 View - get url field
How do I get the URL, not the link html for a taxonomy field in my view.

For Drupal 7 I found this ticket: How do I get the raw URL as a field in Views?

This mentions getting the content: path - but this doesn't show up as an option.

--- Updated ---

I am creating a block view, not sure that matters. I have no path option, I actually am not seeing any content in the field type options.

# Answer
You can do the following.

1. Add Taxonomy ID field too your view
2. In your template or rewrite use the following as your url `{{url('entity.taxonomy_term.canonical', {'taxonomy_term': tid})}}` or `{{path('entity.taxonomy_term.canonical', {'taxonomy_term': tid})}}`
> 3 votes

# Answer
Same problem, I solved it by doing:

* Add a field "Taxonomy term: Term ID \[hidden\]" (make it hidden or not)
* Ensure that this field is in first position (if not, rearrange the fields order)
* Add a field "Global: Custom text"
* Put "{{ path('entity.taxonomy\_term.canonical', {'taxonomy\_term': tid}) }}" (thx @steven) in the "Text" section in the settings modal of this field.
> 2 votes

---
Tags: views, taxonomy-terms, 8, path-aliases
---


# Question
Title: Contact form redirects to homepage without showing submission information
I am using default contact form available in D7 under module section. The problem is that contact form redirects to the homepage. It doesn't show any information about submission, such as "Your message has been sent" etc etc. Instead it redirects to home page immediately.

I don't want the contact form to redirect. It should stay here and should show the submission information/message.

# Answer
> 1 votes
You can use hook\_form\_alter to hook into the contact form and change the default submit behaviour. So instead of redirecting when the form submits, you can just omit that part and display the status message.

```
function mymodule_form_alter($form, &$form_state, $form_id ) {
  if ($form_id == 'contact_site_form') {
    // Use our own custom submit function for the contact form.
    $form['#submit'] = array('my_custom_submit');
  }
}

function my_custom_submit($form, &$form_state) {
  drupal_set_message(t('Success.'));
}

```

# Answer
> 0 votes
At least you can **make sure that a message displays with the help of Rules module**.

Creating a rule that will display a message on the site when a contact form it submitted...

It's a start.

---
Tags: 7, emails
---


# Question
Title: Change the images URI values within an array
In a custom module of services 3.x Drupal 7 that queries the database, I get the values of the URIs of some images within some nodes.

This is part of module:

```
$res = db_query("SELECT node.nid AS nid, node.title AS title, body.body_value AS body, fm.uri AS uri
FROM {node} node
INNER JOIN {field_data_body body} ON body.entity_id = node.nid
INNER JOIN {field_data_field_header_image header} ON header.entity_id = node.nid
INNER JOIN {file_managed fm} ON fm.fid = header.field_header_image_fid
WHERE ((node.status = '1') AND (node.type IN ('tiendas')))
ORDER BY nid DESC");

foreach ($res as $cupon) {
$resultados[] = $cupon;
}
return resultados;

```

And this the json returned by the web services:

```
[
 {
  "nid": "6",
  "title": "Negron Beach Bar",
  "body": "<p>Este es el descuento de Negron</p>\r\n",
  "uri": "public://negron.png"
 },
 {
  "nid": "5",
  "title": "PizaPuck",
  "body": "<p>Este es el descuento de PizaPuck</p>\r\n",
  "uri": "public://pizapuck.png"
 }
]

```

But I need the full url. Not the URI. The json should look like this:

```
 {
  "nid": "5",
  "title": "PizaPuck",
  "body": "<p>Este es el descuento de PizaPuck</p>\r\n",
  "uri": "http://example.com/site/default/files/pizapuck.png"
 }

```

If I use this from below I get the url I need (in $path), but I have to put the URI value by hand:

```
$uri = "public://pizapuck.png"; //by hand
if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
$path = $wrapper->getExternalUrl();
}

```

How can I do to replace every URI value inside the array? I need to extract every value of URI, replace it with the path value, and put it back into the array? I understand this is basic and simple, but my knowledge of php, pdo, ppo and mysql are quite poor. Any help on this matter thank you in advance.

# Answer
I think you will have success with

```
file_create_url("public://pizapuck.png");

```

so

```
for ( $i = 0; $i < count($resultados); $i++){
  $resultados[$i]['uri'] = file_create_url($resultados[$i]['uri']);
}

```

would loop through your results and change them. (untested code typed directly in here).
> 0 votes

# Answer
Well, finally after reading and reading and trying everything, this is what worked for me:

I have created a function that replaces the URI with the complete URL.

`function uritourl($uri){
 if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
 $path = $wrapper->getExternalUrl();
 return $path;
 }
}`

And inside a for I have called it to replace every value in the array.

`foreach ($res as $cupon) {
 $resultados[] = $cupon;
 }
for ( $i = 0; $i < count($resultados); $i++){
 $uri = $resultados[$i]->uri;
 $resultados[$i]->uri = uritourl($uri);
}
return $resultados;`

There will be more elegant, safe or quick ways to do it, but my knowledge is very scarce. I hope this helps someone.
> 0 votes

---
Tags: uri, services
---


# Question
Title: Remove novalidate attribute from webform for client side validation
I have installed webform and client side validation extensions on my drupal project. The problem is in the webform's `form` element `novalidate` attribute is appearing, which cancels the client side validation.

In webform general settings I have unchecked the disable client side validation:

And finally in my form settings I have unchecked the disable client side validation:

Cleared cache but the `novalidate` attribute is still showing. Is there any way to remove this attribute from the form?

# Answer
The Clientside Validation module is automatically adding the novalidate attribute to the form.
> 2 votes

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


# Question
Title: Log into Drupal using drush uli via CURL on the command line
I'm trying to execute a CURL request via command line which uses `drush uli` to log into my site as an administrative user. Then it's redirected to another destination url.

It works if the redirected url is a non-admin path available to anonymous users, but admin paths return a 403 Forbidden, which is something my site does for anonymous users trying to access admin pages.

**This works:**

`curl -vk -L $(drush uli admin_username /node/1)`

**This returns HTTP 403 forbidden:**

`curl -vk -L $(drush uli admin_username /admin/structure)`

The optional `path` parameter is being redirected to after logging in, but it's like when CURL gets there... it's not logged in anymore and is seeing the response as if it were an anonymous user.

Anyone experience this?

# Answer
Thanks to https://spinspire.com/article/automating-drupal-user-login-and-maintaining-session-curl, my issue was solved by using the --cookie-jar CURL option to maintain my session cookie while drush redirected to the admin path after generating a one-time login link.

Here's my final working command:

`curl --cookie-jar cookie.txt -vk -L $(drush uli admin_username /admin/structure)`

This results in an HTTP 200 response from `/admin/structure`.
> 0 votes

# Answer
Is your site redirecting from http to https when you access admin pages? If so, try to set the --uri parameter you provide to Drush to an https instead of http protocol, and see if that works better.
> 0 votes

# Answer
Your `curl` fails, because it has problem passing the cookies between the redirects. Wget should be more suitable tool for this tasks, e.g.

```
wget -qO- $(drush -l http://mysite.local uli --no-browser admin admin/structure)

```

Note: To test the output in human readable format, you can pipe the output to `html2text` command.

To retrieve the page using `curl`, you can try the following shell script by using user credentials:

```
#!/usr/bin/env bash
url="https://www.example.com"
uri_php="/admin/structure"
user=admin
pass=admin
form_build_id=$(curl -s $url/user | grep -o 'form-[^" ]\{40,\}')
cookie=$(curl -sX POST -d "name=$user&pass=$pass&form_id=user_login&op=Log+in&form_build_id=$form_build_id" $url -D- | grep -o "SESS[^;]\{60,\}")
content=$(curl -s -H "Cookie: $cookie" ${url}${uri_php})
echo $content

```
> 0 votes

---
Tags: users, drush, cron
---


title: Dynamic view filter value

text:
# Question
Title: Dynamic view filter value
I'd like the ability to change a View's filter value prior to rendering, specifically add a taxonomy filter to certain pages. The reason I need this, is to have one Views block, and the ability to filter based off the URI, without adding a contextual taxonomy id to the URI. I haven't been able to find a way to handle this in any hook, but I think that's where I should be looking. I've been using the `MODULE_views_pre_view` hook without any luck.

Right now, the only way I've gotten around this is to duplicate the Block over and over again, and it's starting to get messy.

I've found several articles, but they're all for Drupal 7.

# Answer
> 3 votes
I've figured out the problem after lots of guessing. You'll need to use a contextual filter and use the `hook_views_pre_view` hook in a custom module to alter the `$args` variable.

```
function MODULENAME_views_pre_view($view, $display_id, &$args) {
    if ($view->id() === 'view_machine_name') {
        $args[0] = 'your value';
    }
}

```

---
Tags: views, 8
---


# Question
Title: How to modify the link titles shown in /node/add page?
I can modify the menu item title implementing the hook\_menu\_links\_discovered\_alter() hook, as illustrated in this screenprint:

I changed the menu item title to "*Article (Only One Article can be created and edited)*".

But the problem is that the same item is shown also in the `/node/add` page but the title of that link is not changed because it is shown by a controller. As illustrated in the above image also, the menu links are changed but the link in the `/node/add` page remains without changes, which is still just "*Article*".

How I can change that value also, i.e from "*Article*" to "*Article (Only One Article can be created and edited)*", so that it matches with the menu item title?

# Answer
You should copy template\_preprocess\_node\_add\_list() into your module or theme and customize. I would advise against trying to change the value in the node type because it's the name of the bundle type across the site. It will show many places you don't want to update.

For example, to update the article link:

```
function mytheme_preprocess_node_add_list(&$variables) {
  foreach ($variables['content'] as $type) {
    if ($type->id() == 'article') {
      $variables['types'][$type->id()] = array(
        'label' => $type->label() . ' (Only one article can be created and edited)',
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label() . ' (Only one article can be created and edited)', new Url('node.add', array('node_type' => $type->id()))),
        'description' => array(
          '#markup' => $type->getDescription(),
        ),
      );
    }
  }
}

```

Another alternative to the preprocess function is just to copy /core/modules/node/templates/node-add-list.html.twig into your theme and add your custom rules there.

**UPDATE:**

Due to the question's particular requirements, I'm adding another solution that works without altering the seven theme (that conflicts with my solution above). In the solution below, we alter the output of $node\_type-\>label() conditionally:

```
function mymodule_entity_type_alter(array &$entity_types) {
  $entity_types['node_type']->set('label_callback', 'mymodule_node_type_label');
}

function mymodule_node_type_label(NodeType $type) {

  if (\Drupal::routeMatch()->getRouteName() == 'node.add_page' && $type->id() == 'article') {
    return $type->get("name") . ' (You can only add one of these)';
  }
  return $type->get("name");
}

```

**UPDATE:**

Here's another solution that works with the seven theme. You can alter the particular node types you like in the preprocess function in your custom module. This will only alter their labels within this context.

```
function mymodule_preprocess_node_add_list(&$variables) {
  $article_type = $variables['content']['article'];
  $variables['content']['article']->set('name', $article_type->get('name') . ' (Only one article can be created and edited)');
}

```
> 6 votes

# Answer
While @oknate answer is perfect for the original question, in this case an approach in a module could be to replace the NodeController class with a custom class, and use in `addPage()` a custom template or return a build array with the links directly:

**NodeController::addPage()**

```
$build = [
  '#theme' => 'node_add_list_custom',
  ...
  ],
];

```

Then set the custom controller class for the route `node.add_page` in a RouteSubscriber .
> 2 votes

---
Tags: 8, navigation
---


title: Commerce Kickstart on secure server

text:
# Question
Title: Commerce Kickstart on secure server
I am in the process of building a Commerce Kickstart 2 site and need some guidance.

From what I can see it is now recommended that e commerce sites are fully hosted on a secure server.

I have in the past looked after a non commerce Drupal site on a standard server.

So my question is apart from having a SSL certificate installed do I need to do any other work to the site or is it a case of just uploading via the hosts control panel onto the secure server as I would with a normal server.

If it's not going to be that easy any advice please

# Answer
Yes it should be that easy, Drupal doesn't tend to mind what protocol it's served under. I say "should" because who knows what contrib/custom modules you have that might be doing who knows what, but in my experience contrib tends to be pretty good and you can sanity check the custom modules before implementing anyway.

You'll probably want to un-comment the http -\> https redirect in .htaccess (or implement similar in the vhost if you're using something other than Apache), that way any errant insecure requests will be upgraded before they hit Drupal.

A useful check is to crawl a test version of the secure site (e.g. with Integrity on a Mac) and look for requests for insecure resources. If you see any, you can check the referring URLs to find out where the insecure request comes from (link, iframe, script tag, etc), and use that as a jumping point to find out which module/sub-system is responsible.
> 1 votes

# Answer
Thanks Clive for your help. I have now managed to get my site setup but did have a few issues so this may be of use to others at some point. The site is a Commerce Kickstart2 on a shared server. The hosting was set up for me and a link to the control panel was provided. On uploading all seemed to be fine, I put the site into maintenance mode and logged out only to then find I could not get back into the site ( by putting user/login ) Next day re installed site and tried again, same thing no login. After some searching I found a way to get back in using phpmyadmin. More searching found Clean URLs needed to get the login to work via the address bar. Also found a comment that Htaccess is used a lot to control Drupal so looked and yes I had one in the files list, But for some reason I opened the file only to find it was empty. What I think had happened is the Htaccess file was created by my host but the Drupal install having found a copy did not replace it. Pasted in the original content and all worked fine. Now for the secure part https in my searching I came across the Htaccess module installed it set to run as secure and all seems to now work. Hope this help someone else.
> 0 votes

---
Tags: commerce, ssl
---


title: Webform tokens for submitted images

text:
# Question
Title: Webform tokens for submitted images
I'm theming the email that a webform submission generates, and I want to create fqdn'd links to the images that the submitter has uploaded.

I used `[submission:values:photo:nolabel]`, but that generates a url which links to `http://sites/default/files/webform/index1_7.jpg`. Obviously that URL is broken. Because it's a token string, I can't manipulate it with php string manipulation functions, to take off the `http://` part.

The same thing happens with `[submission:values:photo_2]`.

I want to get just the path part, so that I can construct a proper link. I've looked in "Available Tokens" under the webform configuration, but that just lists what I've already tried.

What token gives me just the path to the image on the site?

# Answer
It turns out that there is some later template processing, or perhaps an email client display issue, that is causing my links to be displayed as relative paths.

However, in arriving to this conclusion, I was able to construct the URL from the submitted values.

First, get the ids of the webform components that are uploaded files. These are in the `$submission->data` array.

Then, load each like so:

```
foreach ( $fids as $fid ) {
    $file = file_load($fid);
    $url = file_create_url($file->uri);
}

```
> 0 votes

---
Tags: webforms, tokens
---


title: Custom entity datetime field definition

text:
# Question
Title: Custom entity datetime field definition
I created an entity in a module, using code. I generated skeletons with `drupal console generate:entity:content` (without bundles), and then added a datetime field to my TestFieldEntityItem.php, in `baseFieldDefinitions()`.

```
$fields['test_date_incode'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Test date'))
  ->setDescription(t('Test.'))
  ->setRevisionable(TRUE)
  ->setSettings([
    'datetime_type' => 'date'
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'datetime_default',
    'settings' => [
      'format_type' => 'medium',
    ],
    'weight' => 14,
  ])
  ->setDisplayOptions('form', [
    'type' => 'datetime',
    'weight' => 14,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

I can add data to my entity, without problem, but if I want to add another field (a simple text field) through the UI, I get this error:

> Un problème est survenu à la création du champ test\_text : The "datetime" plugin does not exist.

(In English, the error message is *A problem occurred creating field test\_text: The "datetime" plugin does not exist.*)

The field is created, but I don't like this error. It seems my code to create the datetime field is not the right one. I use the Calendar module, if this could have any incidence.

# Answer
> 6 votes
Hard to tell which plugin is missing. A guess would be it is a missing field widget plugin which causes the error when you try to add a new field to the default form mode. Then change the plugin name to something like this:

```
  ->setDisplayOptions('form', [
    'type' => 'datetime_default',

```

If this is not the error, then provide a full error message with a backtrace.

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


# Question
Title: How do I troubleshoot a jQuery/AJAX issue?
On a current Drupal Commerce installation, I just started experiencing issues where a field is not updating after a jQuery click event.

When a user selects an option, the price typically updates for several of the products on our store. When adding the item to the cart, the correct price is shown. (While helpful on my end that the customer is being charged the right price, it's not great that they cannot see the right price until it is in the cart.)

Everything was working well. No updates were pushed for our distribution and added modules, but this feature is no longer working.

From the Chrome Console, I pulled the error msgs below. How do I troubleshoot? Should I just restore a backup?

```
ui.spinner.min.js:7 Uncaught TypeError: Cannot read property 'msie' of undefined
at ui.spinner.min.js:7
at ui.spinner.min.js:22

```

`jquery.formalize.js:13 Uncaught TypeError: Cannot read property 'msie' of undefined
 at jquery.formalize.js:13
 at jquery.formalize.js:135
commerce_kickstart_product_ui.js:6 Uncaught TypeError: $(...).spinner is not a function
 at Object.attach (commerce_kickstart_product_ui.js:6)
 at Object.<anonymous> (drupal.js:76)
 at Function.each (jquery.min.js:4)
 at Object.Drupal.attachBehaviors (drupal.js:74)
 at HTMLDocument.<anonymous> (drupal.js:504)
 at c (jquery.min.js:4)
 at Object.fireWith [as resolveWith] (jquery.min.js:4)
 at Function.ready (jquery.min.js:4)
 at HTMLDocument.q (jquery.min.js:4)`

# Answer
It is because you are using jQuery 1.9 or superior.

To fix it, use jQuery Update version 7.x-3.0 and enable the jQuery Migrate plugin.
> 0 votes

---
Tags: javascript, ajax
---


# Question
Title: How to do a lookup of existing nodes in the input form?
I want to create in Drupal 8 a content type called **Book** with some fields you'd expect to be associated with it. Title, Author, Date, ISBN, URL

(I want two other content types: **"Book Review"** and **"Book Author.**").

I expect to do a lot of different things with books; it's much easier to have a separate content type for it which I can reuse.

The user (or the admin) would initially use the input form to publish the "Book" (i.e., To Kill a Mockingbird, Great Gatsby, etc)

Next a user having the "**Book Reviewer**" role would have an input form to publish his review (Title, a text field containing the review, a summary, rating) and publication date.

Here's the thing I don't understand.

Tom (who has the **Book Reviewer** role) would log on, select "Add Book Review". For this to work, Tom would need some way in the input form to look up the available book titles already inputted by users in order to choose the specific book he wants to review.

Can you accomplish this in Drupal 8? What is this functionality called? Could this reverse lookup be easily done from the **Book Review** input form? I'm unsure exactly how to implement this. I've seen explanations about how you can look up a specific user in the input form, and maybe from the DB point of view, all nodes are the same. But I'm not sure if looking up users is a special case.

Some more details:

1. I have seen that relationships are a way to connect fields from two different content types. But I'm unsure if you could display this kind of lookup function in the input form!
2. I can' predict how many books will be added or need to be looked up (maybe 50-1000?). But is there any hard limitation on book nodes you could search through?
3. Is this something you could do through Drupal core without needing to make a module?

# Answer
R3: You don't need to write any code :-)

R1: The relations are managed with the field Reference by content (provided by core) take a look inside the *Add a reference field to content type* section in How To Reference Nodes in Drupal 8 + Views Relationships Display

Then you can go to configure your content type display mode and form display mode to change the widget if you want another different from the default widget. See Exploring the New Drupal 8 Display Modes and How "form modes" work in Drupal 8 and how to add and edit them

R2: You can have 1000 books without problem, in this case I recomend to use the autocomplete widget.

If you want to add more functionalities to your relation you can use the following modules:

Entity Reference Views Select

> A module for those who need their Entity Reference Views fields to be displayed as a select list, checkboxes or radio buttons in forms.

Inline Entity Form

> Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form. Existing entities can also be referenced.
> 3 votes

---
Tags: 8, forms, views
---


# Question
Title: How to show another text if field val 0?
```
{% for item in items %}
    {% if item.content %}
        <div class="result-features__body">
            <p class="result-features__title">balance</p>
            <p>Yes {{ item.content }}</p>
        </div>
    {% else %}
        <div class="result-features__body">
            <p class="result-features__title">balance</p>
            <p>Nope</p>
        </div>
    {% endif %}
{% endfor %}

```

My field is integer. I try all if (is null, is same as, etc...) but nothing works.

# Answer
> 0 votes
AFAIK this is the correct way:

```
{% for item in items %}
    {% if item.content == 0 %}
        <div class="result-features__body">
            <p class="result-features__title">balance</p>
            <p>Yes {{ item.content }}</p>
        </div>
    {% else %}
        <div class="result-features__body">
            <p class="result-features__title">balance</p>
            <p>Nope</p>
        </div>
    {% endif %}
{% endfor %}

```

---
Tags: theming, 8
---


# Question
Title: Getting index of item in items inside twig template
If I use any loop in Drupal, I can get loop.index to get the index of looped item. - Ref#1

For example -

```
    {% for tag in content.some_array %}
      <div class="item-count-{{loop.index}}">{{ tag.content }}</div>
    {% endfor %}

```

This is a field containing paragraph type -

`field--field-container.html.twig`

and its content is `{{items}}` (`{{items|length}}` gives the desired count)

The above template iterate through it's items and include the following template multiple times- `paragraph--multiple-blocks.html.twig` and its html is

```
    <div class="multiple-blocks multiple-block-count-{{loop.index}}">
    =====CONTENT=====
    </div>

```

But I cannot get the loop.index (Ref#1) in the `paragraph--multiple-blocks.html.twig` template. I tried (surely google search shows all links visited) `kint()` debugging but could not get anything related to the count or index of the item iterated.

I will be grateful to any guide/help (don't want to code in PHP) close to get this done in twig files will.

# Answer
> 1 votes
You can't, because the loop index is local. And you don't need a class with the index in the paragraph when you have it in the surrounding div for targeting it in CSS.

There is also a fundamental aspect with rendering referenced entities. They are cached and not necessarily rebuild when the order in the field changes. This is even more problematic for other entities than paragraphs, which can be used in more than one place in different orders.

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


# Question
Title: How to call preprocess function for a custom template with more than one word in the template name?
I have a custom module that I've defined a block with a template file.

In my modules `.module` file, I have a preprocess function...

`/**
 * Implements hook_preprocess_short_login().
 */
 function mymodule_preprocess_short_login(&$variables) {
 // code
 }`

My theme file is named `short-login.html.twig`

This does not work. With other templates and preprocess functions, I have always been able to name the function by replacing the hypen (-) with an underscore (\_), but this did not work for my custom template file.

To test, I renamed the template file and all the places that call it.

`/**
 * Implements hook_preprocess_shortlogin().
 */
 function mymodule_preprocess_shortlogin(&$variables) {
 // code
 }`

Rename theme file... `shortlogin.html.twig`

This works and all my code executes. This is fine for a workaround, but I know there will be cases when I'd like to name my template files with more than one word.

# Answer
The naming schema of the preprocess hook `hook_preprocess_HOOK()` contains two HOOKs.

The first one at the beginning is a module/theme name and the second at the end is a theme hook, which is an array key of the template definition in `hook_theme()`:

```
function hook_theme($existing, $type, $theme, $path) {
  return [
    'forum_display' => [
      'variables' => ['forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL],
    ],
    'forum_list' => [
      'variables' => ['forums' => NULL, 'parents' => NULL, 'tid' => NULL],
    ],
    'forum_icon' => [
      'variables' => ['new_posts' => NULL, 'num_posts' => 0, 'comment_mode' => 0, 'sticky' => 0],
    ],
    'status_report' => [
      'render element' => 'requirements',
      'file' => 'system.admin.inc',
    ],
  ];
}

```

For the theme hook only alphanumeric and underscores are allowed.
> 0 votes

---
Tags: theming
---


# Question
Title: How to produce markup from a custom views field (FieldPluginBase based) render method in D8?
I've created a custom views field following the excelent Creating a custom Views field in Drupal 8 guide. The `render` method returns the desired output, except that it's being sanitized somewhere down the line and thus the html markup comes out as plain text on the page.

I'd rather put the html markup into the theme, but there doesn't seem to be such thing as

views-view-field-`<fieldname>`.html.twig

in Drupal8 ?

# Answer
I can output HTML using my render method. Take a look:

```
  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {

    $field_abnormal_category = $this->view->field['field_abnormal_category']->original_value->__toString();

    if($field_abnormal_category == 'No') {
      $field_category_image = $this->view->field['field_category_image']->original_value->__toString();
    }
    else {
      $field_category_image = '';
    }

    return [
    '#type' => 'inline_template',
    '#template' => $field_category_image
    ];

  }

```
> 3 votes

---
Tags: views, theming, entities
---


# Question
Title: FieldPluginBase: How to test based on views field raw value?
I know that the render method is not the right place to do conditional logic but I have no clue where I should implement my tests.

This is my render method I want to access the raw value of a field to do a test on it (conditional field):

```
  public function render(ResultRow $values) {

    $field_abnormal_category = $this->view->field['field_abnormal_category']->original_value->__toString();

    if($field_abnormal_category == 'No') {
      $field_category_image = $this->view->field['field_category_image']->original_value->__toString();
    }
    else {
      $field_category_image = '';
    }

    return [
    '#type' => 'inline_template',
    '#template' => $field_category_image
    ];

  }

```

The `original_value` object is returning the translation not the original string.

How can I access the original value of my field (not translated)?

# Answer
> 1 votes
For the untranslated field value get first the untranslated entity:

```
if ($entity = $this->getEntity($values)) {
  $untranslated_entity = $entity->getUntranslated();
  $untranslated_value = $untranslated_entity->field_example->value;
}

```

---
Tags: views, 8
---


# Question
Title: Can a coupon be programmatically added to an order using the add to cart subscriber?
I'm attempting to add a coupon to an order when an item is added to the cart. I've added an event subscriber for `commerce_cart.entity.add`. Within the subscriber, I use `$to_apply->getPromotion()->apply($event->getCart());`.

This does end up in `Promotion::apply()` and does call `$offer->apply()`, but the coupon doesn't seem to actually get applied. I've tried to see if, once we arrive at /checkout/{order\_id}, the promotions/coupons are reset. AFAICT, they are not.

I have confirmed that I can manually apply the coupon once on /checkout/{order\_id}.

What am I missing?

# Answer
> 1 votes
Got an answer via Slack. You only need to update the `OrderInteface` and set the `coupons` property, then resave the order. `PromotionOrderProcessor` handles applying the coupon to the order.

Something like this should work within your event subscriber:

```
  /** @var \Drupal\commerce_promotion\Entity\Coupon $to_apply */
  $to_apply = $coupon
  /** @var OrderInterface $cart */
  $cart = $event->getCart();
  $cart->set('coupons', $to_apply);
  $cart->save();

```

---
Tags: commerce
---


title: How to pre-populate fields in checkout?

text:
# Question
Title: How to pre-populate fields in checkout?
We have a product that is being sold with Drupal Commerce (using Drupal 7). This specific product is going to be advertised in more ways than just the Drupal site (e.g. email, other sites).

These other sites can have a form in which the user enters some basic information (Name, phone, email). This data is sent to Drupal (curl), a cart and session is created (anonymous unless the user is logged in our site) and the session ID is sent back to the calling website.

The user is redirected to our Drupal site, and the session is restored using the id that was passed.

Everything is working fine, but the user has enter the name, phone and email twice because Drupal tries to pre-populate the checkout fields with the user data, and in this case the user is anonymous, even though I have the user data from the first call.

Is it possible to add this information (name, email, phone) after calling `commerce_cart_product_add()` for anonymous users? The fields in checkout should get pre-populated even if the user is anonymous.

# Answer
> -1 votes
You can do one of two things: store the incoming data in the session somehow and alter it into the appropriate fields via hook\_form\_alter() or immediately create the relevant customer profiles for the session and reference them from the cart order you create. Default rules in Drupal Commerce will handle assigning those customer profiles to any user account that gets created during checkout for your anonymous sessions.

---
Tags: commerce
---


title: How do I override clone block?

text:
# Question
Title: How do I override clone block?
I cloned the *Block property* view and renamed it *Block portfolio*.

When I change the content type, the *Block property* and *Block portfolio* still use the same content type.

>

How do I override it?

# Answer
When you're configuring the filter, at the top, select **For** `This block (override)` or `This Page (override)`

Example:
> 2 votes

---
Tags: 7, views
---


# Question
Title: Are user browser information and ip address available as tokens in Rules?
I am sending an email to admin from contact form. In the email I want to send the user browser information like browser name and version and the user ip address. But I'm unable to see the tokens for these values?

I want the browser info and ip address for both logged-in and anonymous users.

Are these tokens available in the Rules module? Or I will have to create custom tokens?

# Answer
> 3 votes
Use `[current-user:ip-address]` token for IP address of the current user.

For browser related token you have generate it using **token\_generate** API.

> function **token\_generate** use to generates replacement values for a list of tokens.

# Answer
> 1 votes
If you'd enable the Visitors module (disclosure: I'm its maintainer), it would already capture the info you're looking for.

Here is just a random pick of such capture info:

This info can be used to displayed it to authorized users visiting the site, whereas you could include an appropriate link to the relevant Visitors info in the eMail you want to send (using the Rules module).

# Answer
> -1 votes
if you want browser info them use this...

```
<code> <iframe src="http://ulvis.net/browser.php"></iframe></code>

```

look like

---
Tags: 7, rules, tokens
---


# Question
Title: Modifying $view in hook_views_pre_render()
I'm using Drupal 8.0.5, and need to force a title on a View.

I've tried various Views hooks, but will focus on hook\_views\_pre\_render().

There's a `ViewExecutable $view` taken as an argument, which is *not* passed by reference.

I've tried:

```
function mymodule_views_pre_render(ViewExecutable $view) {
  $view->setTitle('foo');
  // $view->save(); // I've also tried this
}

```

I've gone through step-debugging to ensure it's getting called, but it seems the setTitle method does not affect the output that renders. I've also set my theme back to Seven to ensure there's not a theme issue involved.

I'm also happy to embed the View using a custom block, but I am running into the same issue there.

How does one modify a ViewExecutable object properly?

# Answer
> 2 votes
You should be able to override the title by implementing `hook_preprocess_views_view`:

```
function MYMODULE_preprocess_views_view(&$variables) {
  $variables['title'] = 'Foo';
}

```

The View object is available in `$variables['view']` if you need it for context.

Incidentally, I think you'd be able to use the `setTitle()` method on the View object itself if you implement `hook_views_post_execute` or `hook_views_post_build` (but I haven't tried either).

# Answer
> 3 votes
```
function hook_views_post_render(\Drupal\views\ViewExecutable $view) {
   if ($view->id() == 'viewid') {
    // Set the view title.
    $view->setTitle('NEW TITLE');
   }
}

```

---
Tags: 8, views
---


# Question
Title: Override field module function in custom module?
I want to override `field_sql_storage_field_storage_write()`, defined in /modules/field/modules/field\_sql\_storage/field\_sql\_storage.module.

I tried with `MYMODULE_field_storage_write_alter($entity_type, $entity, $op, $fields)`, but it doesn't work.

How should I override that function?

# Answer
> 0 votes
You could try hook\_field\_storage\_info\_alter

Other candidates are

1. hook\_field\_insert
2. hook\_field\_update

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


# Question
Title: How do I add an additional “Cancel account” operation link?
On Drupal 8, I'm trying to modify /admin/people to have the cancel button appears under Edit link in operations.

What's the easiest way to do this?

# Answer
> 0 votes
It can be achieved by rewriting operation links field in views:

```
<a href="/user/{{ uid }}/edit">edit</a>
<a href="/user/{{ uid }}/cancel">cancel</a>

```

---
Tags: views, 8, users
---


# Question
Title: How to track an action when user creates a node of a specific content type?
I use Drupal 7 and I want to track an action when user creates a node of a specific content type.

I installed the Facebook Pixel and Facebook Tracking Pixel modules, but they don't support my needs. Is there any way to implement this?

# Answer
I would use the Rules module, which allows for dozens of variations of tracking. As an example, here is a prototype of a rule, in Rules export format, to illustrate the possibilities:

```
{ "rules_find_links_in_body" : {
    "LABEL" : "Find links in body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "OR" : [
          { "text_matches" : {
              "text" : [ "node:body:value" ],
              "match" : "http(|s):\/\/+",
              "operation" : "regex"
            }
          },
          { "text_matches" : {
              "text" : [ "node:body:value" ],
              "match" : "ANotAllowedTextStringInBody",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Node body contains an URL ..." } }
    ]
  }
}

```

Some more details about the above prototype rule:

* **Rules Event** = After saving new content of type "Article" (adapt the type to fit your needs).
* **Rules Conditions**:
    + Check if the current user is an authenticated user.
    + Perform a text comparison, using a **Regular Expression** as the **Comparison operation** (which you can perfectly do in Rules, without using the PHP filter for it). For the actual regular expression, this rule uses `http(|s)://+`, which will discover strings that start with either `http://` or `https://`. Should you have additional / similar requirements to discover variations of this (say some other string like `ANotAllowedTextStringInBody`), another Rules Condition (with an *OR*) will take care of that also.
* **Rules Action** = Show a message on the site (adapt the message to fit your needs), and/or add other relevant Rules Actions ... Such as:

**Voilà**, easy as that ...
> 0 votes

---
Tags: 7, nodes, users, social-network
---


# Question
Title: Restricting "view content" to members of a group
I would like to make a site with content that anonymous users can read, and private content that only group members can read.

How do I achieve this? I have installed Group, but any group content I add can be viewed by anonymous users.

# Answer
> 0 votes
Some basics about he Group module to be aware of:

* Make sure you enable `gnode`, a submodule of the Group module.
* For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
* Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

It seems that you would want to grant access to what, in Group, is called "Members" (similar to what in your question is called 'Group members'). But you woudn't allow access to "Anonymous" (site visitors that are not logged it). However, you also need to think about which access you want to give to "Outsiders" (= logged in users who are not a member of a group).

With the above in place, it's just a matter of assigning a node to a Group: based on how you configured the roles and permissions, the Group module will allowed/deny access for any user.

### More info

Refer to "How to create collections of content that can be accessed by users with various access levels?" for more info about all this.

---
Tags: 8, users, group
---


# Question
Title: How do I create a template file for the custom node view mode?
I am using Drupal 8, and I created a new view mode for the *News page* content type, in the custom display settings section.

>

How can I create a template file for this view mode?

# Answer
> 6 votes
According to the D8 docs, you'd need to create a file in your your custom theme with this naming convention:

`node--[type|nodeid]--[viewmode].html.twig`

So if I had a content type of `person` and a view mode of `Teaser` my template name would be `node--person--teaser.html.twig`. Be sure to follow the machine name patterns if you're using spaces in your custom view mode.

Generally speaking, I like to put it in a `templates/node` directory of my theme so that other devs can find it quickly. Whether you copy the base node template (`core/modules/node/templates/node.html.twig`) or start from scratch is up to you.

Also, if you turn on theme debugging, Drupal will output in HTML comments a list of template name suggestions, starting from most specific to least specific filenames.

---
Tags: theming, entities
---


# Question
Title: Custom field type deletes data from table when I modify the page
I'm using Drupal 7 and I have a problem with custom field type generated by field type generator.

I attached this field to a content type, and set his value to unlimited. When I create content type and add values it works fine. So, when I modify the page, values are deleted from database and I must add again. Here attach the functions generated by field type generator.

```
/**
 * @file
 * mediatrack module.
 * Media Track field.
 */

/**
 * Implements hook_field_info().
 */
function mediatrack_field_info() {
  return array(
    'mediatrack' => array(
      'label' => t('Mediatrack'),
      'description' => t('The media track'),
      'default_widget' => 'mediatrack_widget_default',
      'default_formatter' => 'mediatrack_formatter_default',
    ),
  );
}

/**
 * Implements hook_field_widget_info().
 */
function mediatrack_field_widget_info() {
  return array(
    'mediatrack_widget_default' => array(
      'label' => t('Default widget'),
      'field types' => array('mediatrack'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function mediatrack_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  switch ($instance['widget']['type']) {
    case 'mediatrack_widget_default':
      $element['mediatrack']['trackid'] = array(
        '#type' => 'textfield',
        '#title' => t('Trackid'),
        '#default_value' => strval(next_trackid($field)),
      );
      $element['mediatrack']['tracktype'] = array(
        '#type' => 'select',
        '#options' => array("---","audio","video"),
        '#title' => t('Tipo traccia'),
      );
      $element['mediatrack']['tracktitle'] = array(
        '#type' => 'textfield',
        '#title' => t('titolo'),
        '#maxlength' => 255,
        '#default_value' => isset($items[$delta]['tracktitle']) ? $items[$delta]['tracktitle'] : NULL,
      );
      $element['mediatrack']['trackdesc'] = array(
        '#type' => 'text_format',
        '#title' => t('Descrizione'),
        '#format' => isset($items[$delta]['trackdesc_format']) ? $items[$delta]['trackdesc_format'] : NULL,
        '#default_value' => isset($items[$delta]['trackdesc']) ? $items[$delta]['trackdesc'] : '',
      );
      $element['mediatrack']['tracksource'] = array(
        '#type' => 'textfield',
        '#title' => t('file'),
        '#maxlength' => 255,
        '#default_value' => isset($items[$delta]['tracksource']) ? $items[$delta]['tracksource'] : NULL,
      );
    // Collapse existing entries, for some UX.
    if (($delta < sizeof($items))) {
      $fieldset_title = t("{$instance['label']} #{$delta}");
    }
    else {
      $fieldset_title = t("New entry for {$instance['label']}");
    }
    $element += array('#type' => 'fieldset');
    $element['#title'] = t('@fieldset_title', array('@fieldset_title' => $fieldset_title));
    $element += array(
      '#collapsible' => TRUE,
      '#collapsed' => ($delta < sizeof($items)),
    );
    break;
  }
  return $element;
}

function next_trackid($field) {
  $fieldname = array_keys($field['storage']['details']['sql']['FIELD_LOAD_CURRENT'])[0];
  $name = $field['field_name'];
  $id = db_query("select max(" . $name . "_trackid) from {" . $fieldname . "};")->fetchfield();
  if ($id == NULL) {
    return 1;
  }
  else {
    return $id+1;
  }
}

/**
 * Implements hook_field_validate().
 */
function mediatrack_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  if ($field['type'] == 'mediatrack') {
    foreach ($items as $delta => $item) {
      // If field is not considered empty, validate its data.
      if (!mediatrack_field_is_empty($item, $field)) {
      }
    }
  }
}

/**
 * Implements hook_field_presave().
 */
function mediatrack_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  // Structure the field data as expected by the database. Only act when the
  // elements come nested as 'publisher_reference'. Otherwise, no change needed.
  if (!empty($items) && $field['type'] == 'mediatrack' && array_key_exists('mediatrack', $items[0])) {
    foreach ($items as $delta => $item) {
      $items[$delta]['trackid'] = $item['mediatrack']['trackid'];
      $items[$delta]['tracktype'] = $item['mediatrack']['tracktype'];
      $items[$delta]['tracktitle'] = $item['mediatrack']['tracktitle'];
      $items[$delta]['trackdesc'] = $item['mediatrack']['trackdesc']['value'];
      $items[$delta]['trackdesc_format'] = $item['mediatrack']['trackdesc']['format'];
      $items[$delta]['tracksource'] = $item['mediatrack']['tracksource'];
    }
  }
}

/**
 * Implements hook_field_formatter_info().
 */
function mediatrack_field_formatter_info() {
  return array(
    'mediatrack_formatter_default' => array(
      'label' => t('Default formatter'),
      'field types' => array('mediatrack'),
    ),
  );
}

```

This is a mediatrack field. Trackid is set to trackid +1 by default; I have a textfield for test only. When I modify, I can see table with previously added field collapsed, but, when I save, I don't see these fields, and the table is empty, if I don't add anything.

Do I need to set something?

# Answer
> 0 votes
I solved setting 'not null' to FALSE in my field\_schema function, to trackid. Now it works!

---
Tags: entities
---


title: Disable the Comment module

text:
# Question
Title: Disable the Comment module
Is there a way to disable the core Comment module in Drupal 8? The module is enabled by default, but I prefer not to use Drupal comment system and would like to not have it clutter up the GUI for site builders.

I do understand that disabling a module in Drupal 8 is the same as removing it -- perhaps that's why most core modules can't be disabled.

# Answer
In Drupal 8, you cannot anymore disable modules. You can only uninstall a module, but in the case of the Comment module, you first need to remove any *Comments* field. In fact, on /admin/modules/uninstall you will see the following message:

> The following reason prevents Comment from being uninstalled:
>
> * The *Comments* field type is used in the following field: *node.comment*

By default, the *Comments* field is added to every content type.

>

Once you remove that field from every content type, you will be able to uninstall the Comment module from a Drupal 8 site, if there isn't any module that depends from the Comment module. Otherwise, you first need to uninstall first those modules.

As for updating Drupal, updating Drupal doesn't install the core modules you previously uninstalled, not even the ones the profiles you used to install Drupal would install.
> 13 votes

# Answer
Through Drush

```
drush ev '\Drupal::service("entity_field.manager")->getFieldStorageDefinitions("node")["comment"]->delete();'
drush cron
drush pmu comment

```
> 6 votes

# Answer
Yes, you can disable the comment module once every use of the comment fields have been remove.

But you can't uninstall this module in Drupal 8.

For the long answer, see this post : https://www.drupal.org/node/2225029

Even if you removed all the "comment" fields you wouldn't be able to uninstall the comment module.
> 0 votes

---
Tags: 8
---


title: Custom entries in entity view modes?

text:
# Question
Title: Custom entries in entity view modes?
## Background + question

I want to port entdispfieldui to Drupal 8. (issue)

The module allows a site builder to add new entries into an entity view mode, configure and position them among the regular fields. These entries exist per view mode / bundle / entity type.

I am wondering what would be the best way to achieve this in Drupal 8. Is one of the ideas below suitable? Why would I use one over the other?

## Ideas so far

## Idea 1: Extra fields + config entities

hook\_entity\_extra\_field\_info() allows to insert "pseudo" fields per entity bundle, but across view modes. The idea would be to use hook\_form\_alter() to remove the items from those view modes where they don't belong.

I found some documentation on extra fields here: https://www.webomelette.com/creating-pseudo-fields-drupal-8

Entries would be stored as config entities, with keys to determine to which view mode they belong.

For this, I started looking at https://www.drupal.org/docs/8/api/configuration-api/creating-a-configuration-entity-type-in-drupal-8

## Idea 2: Learn from field\_group and Display suite

field\_group does something similar to what I am trying to do. Except that the entries are not pseudo fields, but groups. But still, these are entries or "things" that exist per view mode, and can be created and deleted.

But I found that field\_group does not use a config entity type for this. Instead, in `field_group.entity_display.schema.yml`, I find this:

```
core.entity_view_display.*.*.*.third_party.field_group:
  type: sequence
  label: 'Field group settings on entity view'

```

Similar lines can be found in ds.entity\_display.schema.yml or field\_layout.schema.yml. Although these do not use `type: sequence`. I think this is because they store settings for the view mode itself, not for entries within the view mode.

So I wonder, what does the `core.entity_view_display.*.*.*.third_party...` mean, and why would I use this + type: sequence, instead of a config entity type?

And if I use this method, would it still make sense to work with hook\_entity\_extra\_field\_info() ?

# Answer
> 1 votes
I made it work!

There are many details to consider, so here is just a rough overview.

## Storing the entries.

I decided to store the entries not in config entities, but as raw config entries. This seems easier, and prevents recursion with hook\_entity\_extra\_field\_info().

For each entry, we store:

* Configuration that tells us how the item should be displayed when viewing the entity.
* Optionally, an administrative label and/or a label for visitor consumption.

We do NOT store the weight (order / position between other fields). Thanks to hook\_entity\_extra\_field\_info(), Drupal will do this for us!

We do NOT store an id or machine name as a value within the entry. Instead, the machine name is part of the key referencing the config entry.

Each entry is identified by a key of the format `"entdisp.vme.$entity_type_id.$bundle.$view_mode.$entry_machine_name"`.

entdisp.view\_mode\_entry.schema.yml:

```
entdisp.vme.*.*.*.*:
  type: ignore

```

Obviously this could be more sophisticated, but it works for me.

## Crud forms for add + delete

Similar to field\_group module, create forms to add and delete view mode entries.

E.g. `admin/structure/types/manage/article/display/full` will have an action link "Add EntDisP entry" leading to `admin/structure/types/manage/article/display/full/entdisp/add`.

## hook\_entity\_extra\_field\_info()

Register extra fields per bundle, with placeholders for the label and other settings.

```
/**
 * Implements hook_entity_extra_field_info().
 */
function entdisp_entity_extra_field_info() {

  $ids = \Drupal::configFactory()->listAll('entdisp.vme.');

  $fill = ['', '', '', '', '', ''];

  $defaults = [
    'label' => '_',
    'visible' => FALSE,
  ];

  $extra = [];
  foreach ($ids as $id) {
    $pieces = explode('.', $id) + $fill;
    if (in_array('', $pieces, TRUE)) {
      continue;
    }
    list(,,$entity_type_id, $bundle, $view_mode, $vme_name) = $pieces;
    // $view_mode is not used!
    $extra[$entity_type_id][$bundle]['display']['entdisp_' . $vme_name] = $defaults;
  }

  return $extra;
}

```

## hook\_form\_entity\_view\_display\_edit\_form\_alter()

Alter the `entity_view_display_edit_form`.

In `$form['fields']` and in `$form['#extra']`, we already find one entry for each extra field that we previously registered.

For each of the entry in `$form['#extra']` that begins with 'entdisp\_', do the following:

* Check if the a corresponding entry exists in the settings.
* If not, remove the entry from `$form['fields']` and from `$form['#extra']`.
* If yes, modify the element in `$form['fields'][$name]`, to give it a label and configuration controls. Have a look at `field_group_field_ui_display_form_alter()` and at `EntityViewDisplayEditForm` in core.

This is all a bit tricky and more work than can be explained here. But it is easier than in field\_group, thanks to the trick with hook\_entity\_extra\_field\_info().

## hook\_entity\_view()

In this hook, for each item in $display-\>getComponents(), we

* look up the corresponding config entry.
* add a render element to `$build`.

It can look somehow like this: https://www.webomelette.com/creating-pseudo-fields-drupal-8

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


# Question
Title: How do I view the author of a comment in a view block?
I want to create a view block to display information about the author of a comment.

So I created a comment block and added the fields I missed. My problem, what contextual filter does it need to be added to show only the author of the comment and not all the authors ?

In response to 4K4 :

# Answer
To place a view block next to each comment use the module:

EVA: Entity Views Attachment

Create a new View for `user`, add an EVA display, connect it in ENTITY CONTENT SETTINGS to the Entity Type `comment`, the Bundle `default comment` and as Arguments provide the token for the user id `[comment:author:uid]`. Add a contextual filter for the User ID.

Now the EVA views block appears in the Comment Type and you can place it in Manage Display.

You can also use as Argument the comment id and connect it to the View you have in the question which is based on comments and has the author as relationship.
> 3 votes

---
Tags: views, 8, nodes, comments
---


# Question
Title: How do I show an Open/Save file dialog using an AJAX callback?
In the form builder I have the following code.

```
$form['export_to_pdf'] = [
  '#type' => 'submit',
  '#value' => $this->t('Pdf Format'),
  '#attributes' => array('name'=>'print_pdf',),
  '#ajax'=> array(
    'callback' => '::exportPdf',
    'event' => 'click',
    'effect' => 'fade',
    'prevent' => 'submit',
    'progress' => array(
      'type' => 'throbber',
      'message' => t('Retrieving...'),
    ),
  ),
];

```

The callback function is the following one.

```
public function exportPdf(array &$form, FormStateInterface $form_state) {
  global $base_url;
  $url = "{$base_url}/pdf_templates/report.pdf";
  $response = new AjaxResponse();
  $response->addCommand(new RedirectCommand($url));
  return $response;
}

```

This works, but it doesn't pop up the Open/Save file dialog. It redirects to the PDF file. How do I make the callback show the Open/Save file dialog so that the users can either open or save according to their wish?

# Answer
> 0 votes
For Open /Save Dialog pop up you can use following ajax commands in the ajax callback

```
1.OpenModalDialogCommand
2.OpenDialogCommand

```

**Don't forget to include following namespaces**

```
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\OpenDialogCommand;

In your ajax callback function add like below:
 $content = AjaxTestController::dialogContents();
 $response = new AjaxResponse();
$title = $this->t('AJAX Dialog & contents');

```

Attach the library necessary for using the Open(Modal)DialogCommand and set the attachments for this Ajax response.

$content\['#attached'\]\['library'\]\[\] = 'core/drupal.dialog.ajax';

```
if you need as modal dialog you can use below statement

$response->addCommand(new OpenModalDialogCommand($title,
$content));

```

or only dialog type

```
 $selector = '#ajax-test-dialog-wrapper-1';
    $response->addCommand(new OpenDialogCommand($selector, $title, $content);

```

return $response;

for any reference you can check below files in the drupal directory

> core/modules/system/tests/modules/ajax\_test/src/form/AjaxTestDialogForm

After completing the dialog command ,you can use your redirect command to continue

---
Tags: ajax, theming
---


title: How do I prevent form caching?

text:
# Question
Title: How do I prevent form caching?
I have a form using AJAX that will be used by many users at once, authenticated and anonymous users as well.

What precautions should I take to prevent data leaking between users (especially anonymous)?

I disabled the cache on route level via no\_cache option. Is that sufficient or should I use `\Drupal\Core\Form\FormStateInterface::disableCache()` or maybe something else as well?

# Answer
> 2 votes
> What precautions should I take to prevent data leaking between users (especially anonymous)?

You shouldn't have to do anything special. not even disable render cache.

Form data is only cached *after* the first ajax request and then it is for the specific form build Id (which is unique) only. That means that while the form is generated and cached in the page cache, the first request for every request for every user will rebuild the form from scratch.

There used to be a bug in core at some point in 8.x (long before 8.0) where the new user entity including its UUID was cached on the register form and then only one user could register every 6h because the others had UUID conflicts. The form cache changes fixed this.

---
Tags: 8, forms, caching
---


# Question
Title: Querying a custom entity throws Exception
For a project I am using custom defined entities. One is called "Country" and it has a name and country\_code field.

The entity itself should be translatable for multiple reasons. The name and entity is marked as translatable and the translation of an entity throu Entity API works with no problem.

I wanted to use a custom service to check if a country code exists

```
public function checkIfValidCountryCode($country_code) {

  $query = \Drupal::entityQuery('country');

  $query->condition('country_code', $country_code);

  $result = $query->execute();

  if(empty($result)) {
    return FALSE;
  } else {
    return TRUE;
  }

}

```

but it throws an exception

```
The website encountered an unexpected error. Please try again later.

Drupal\Core\Entity\Query\QueryException: 'country_code' not found in Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable() (line 316 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).
Drupal\Core\Entity\Query\Sql\Tables->addField('country_code', 'INNER', NULL) (Line: 44)
Drupal\Core\Entity\Query\Sql\Condition->compile(Object) (Line: 155)
Drupal\Core\Entity\Query\Sql\Query->compile() (Line: 74)
Drupal\Core\Entity\Query\Sql\Query->execute() (Line: 46)

```

I really wrote it down exactly as defined in my Entity class:

```
namespace Drupal\custom_country\Entity;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\custom_country\CountryInterface;
use Drupal\user\UserInterface;

/**
 * Defines the Country entity.
 *
 * @ingroup custom_country
 *
 * @ContentEntityType(
 *   id = "country",
 *   label = @Translation("Country"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\custom_country\CountryListBuilder",
 *     "views_data" = "Drupal\custom_country\Entity\CountryViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\custom_country\Form\CountryForm",
 *       "add" = "Drupal\custom_country\Form\CountryForm",
 *       "edit" = "Drupal\custom_country\Form\CountryForm",
 *       "delete" = "Drupal\custom_country\Form\CountryDeleteForm",
 *     },
 *     "access" = "Drupal\custom_country\CountryAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\custom_country\CountryHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "country",
 *   admin_permission = "administer country entities",
 *   translatable = TRUE,
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *     "country_code" = "country_code"
 *   },
 *   links = {
 *     "canonical" = "/admin/custom/country/{country}",
 *     "add-form" = "/admin/custom/country/add",
 *     "edit-form" = "/admin/custom/country/{country}/edit",
 *     "delete-form" = "/admin/custom/country/{country}/delete",
 *     "collection" = "/admin/custom/country",
 *   },
 *   field_ui_base_route = "country.settings"
 * )
 */
class Country extends ContentEntityBase implements CountryInterface {
  use EntityChangedTrait;
  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += array(
      'user_id' => \Drupal::currentUser()->id(),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this->get('user_id')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this->get('user_id')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this->set('user_id', $uid);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('user_id', $account->id());
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isPublished() {
    return (bool) $this->getEntityKey('status');
  }

  /**
   * {@inheritdoc}
   */
  public function setPublished($published) {
    $this->set('status', $published ? NODE_PUBLISHED : NODE_NOT_PUBLISHED);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCountryCode() {
    return $this->get('country_code')->value;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    //ID field
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the Country entity.'))
      ->setReadOnly(TRUE)
    ;

    //UUID field
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The UUID of the Country entity.'))
      ->setReadOnly(TRUE)
    ;

    $fields['langcode'] = BaseFieldDefinition::create('language')
      ->setLabel(t('Language code'))
      ->setDescription(t('The language code for the Country entity.'))
      ->setDisplayOptions('form', array(
        'type' => 'language_select',
        'weight' => 10,
      ))
      ->setDisplayConfigurable('form', TRUE)
    ;

    //Version
    $fields['country_code'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Country Code'))
      ->setDescription(t('Country Code in lower case. Examples: ch, de, fr, etc.'))
      ->setRevisionable(FALSE)
      ->setTranslatable(FALSE)
      ->setRequired(TRUE)
      ->setSettings(array(
        'default_value' => '',
        'max_length' => 2,
        'text_processing' => 0,
      ))
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'string',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'string_textfield',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)
    ;

    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The name of the Country entity.'))
      ->setRequired(TRUE)
      ->setRevisionable(FALSE)
      ->setTranslatable(TRUE)
      ->setSettings(array(
        'max_length' => 255,
        'text_processing' => 0,
      ))
      ->setDefaultValue('')
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'string',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'string_textfield',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)
    ;

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Publishing status'))
      ->setDescription(t('A boolean indicating whether the Country is published.'))
      ->setDefaultValue(TRUE)
    ;

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'))
    ;

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'))
    ;

    return $fields;
  }

}

```

I googled pretty much everywhere but could not find what I did wrong.

Can anybody help me?

# Answer
> 2 votes
You are missing `data_table` in your Entity annotation. Add:

```
data_table = "country_field_data"

```

And it should work as expected. And update the entity using something like Drush: `drush entity-updates`

# Answer
> 1 votes
I would try the followings:

* With phpymyadmin (or similiar) checking if the schema of your table (country) is just looking the same as expected based on the country entity type annotation/basefields.
* Maybe you creating process of your entity type was "step by step" and you need to run drush entup or similiar to update your entity schema.
* I would also try to make the same query with `\Drupal::database()->select(...)` or with
`\Drupal::entityTypeManager()->getStorage('country')->loadByProperties([])`

It's indeed very strange that entityQuery is trying to find a basefield in a different table.

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


# Question
Title: How do I disable tooltips for field help text in Bootstrap?
On the user registration page, my help text for fields is displayed as pop-up text when I use the Bootstrap theme, but this doesn't work well on mobile devices, and most of my users are visiting through their phones. How do I get rid of the tooltips?

# Answer
There is a setting for this.

1. admin/appearance/settings/bootstrap
2. Javascript -\> **Uncheck** *Enable Bootstrap Tooltips*
> 5 votes

# Answer
In addition to the GUI way of disabling the tooltips, there are other ways of disabling these tooltips. Following are the options that I know of.

**Option 1:** Admin interface

First and generally best way through the theme settings in the admin interface (see Patrick Kenny's answer)

**Option 2:** theme .info file

Through the `bootstrap.info` file or your own Bootstrap subtheme's info file:

```
; Tooltips
; --------------
settings[bootstrap_tooltip_enabled] = 1
settings[bootstrap_tooltip_animation] = 1
settings[bootstrap_tooltip_html] = 0
settings[bootstrap_tooltip_placement] = 'auto left'
settings[bootstrap_tooltip_selector] = ''
settings[bootstrap_tooltip_trigger]['hover'] = 'hover'
settings[bootstrap_tooltip_trigger]['focus'] = 'focus'
settings[bootstrap_tooltip_trigger]['click'] = 0
settings[bootstrap_tooltip_delay] = 0
settings[bootstrap_tooltip_container] = 'body'

```

**Option 3:** Disable tooltips per element

If you do not want to disable tooltips theme-wide, you should be able to disable them by element. You could use `hook_form_alter()` with underneath setting for most existing forms or set it directly on your form when creating it.

```
// Set #smart_description to FALSE, to disable tooltips
$form['my_element']['#smart_description'] = FALSE;

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: content.field_name does not render anything
i've made a twig file for my 'test' content type called node--test.html.twig. That works fine using {{ content }} to print the node.

I've a custom field with the machine name field\_text, the following prints fine: {{ node.field\_text.value }}

For some reason i cant get {{ content.field\_text }} to work. I also can't get content.body or any other subset of content to work in any node type.

I must be doing something really daft - thanks for the help

# Answer
`content.<field_name>` should work. try adding `{{ dump(content|keys) }}` to your template, does it show anything?
> 2 votes

---
Tags: theming
---


# Question
Title: Initialize form object properties based on url params?
I did see some form classes which set form object properties in the `buildForm()` method.

However, these property values are no longer available in `submitForm()`.

Simplified/incomplete example:

```
class MyForm {

  private $arg0;

  public function buildForm($form, $form_state, $nid) {
    $this->nid = $nid;
  }

  public function submitForm($form, $form_state) {
    $nid = $this->nid;  // $nid will be NULL.
  }
}

```

Actually there are some callbacks where these property values are available. E.g. if you register a `#process => [[$this, 'process']]` callback.

But it is not really surprising that the values are gone in some callbacks. `::buildForm()` is not a constructor.

In some other form classes, they use `$form_state->set($key, $value)` to make data available to `submitForm()`. This works, but it somehow seems ugly.

Another way would be to store these values in the `$form` array as `'#type' => 'value'`, or as `#_my_data' => ...`. Again, I find this ugly.

Is there a more reliable way to initialize object properties on the form object based on url parameters? E.g. to have these parameters sent to the constructor?

Also, depending how I do this, do I need to worry that the data will be serialized?

(To me this seems like a flaw in the form API. But maybe I am missing something. I might open an issue on drupal.org, if the answer does not change my mind.)

# Answer
> 3 votes
Yes, you can use form\_state storage.

Object properties should work fine as well as long as you do not use private, use protected. private conflicts with the DependencySerializationTrait.

And yes, everything you store like that is serialized (unless it is a service, then that trait will remove and restore it) because that's the only way to transport this data across different requests.

# Answer
> 2 votes
If you want to store parameters from the url the most reliable place for this is a form value. This is because the form gets built and rendered without that $form or $form\_state is serialized and stored. And even if it would, the rendered form may be delivered later than 6 hours when the key\_value storage has expired. You can store data in $form\_state or in class properties of the form class under certain circumstances as @Berdir explained, but this depends on when and where you want to set and get the data.

So in general an example to store the parameter `nid` in the form would look like this:

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

  $form['nid'] = [
    '#type' => 'hidden',
    '#value' => $nid,
  ];
  $form['#cache']['contexts'][] = 'url';

}

```

(I don't think this is a flaw, it's more about how html forms work)

---
Tags: 8, forms
---


# Question
Title: How to get a list of entities programmatically?
I wrote custom rules action to get a list of active simplenews subscribers, but I can not process it with "loop" cycle. Action should get list of active simplenews subscribers ("entity\_fetched" array). Then I pass it to "loop" for processing (and to get "list-item" variable) and there are no errors. But when I try to set status message (add action - system - set message) with "list-item:uid", system says: "Data selector list-item:uid for parameter message is invalid". More, I can not select "list-item" token at all. I think, there are some mistakes when the code returns "entity\_fetched" array. There is my code:

```
<?php

   function custom_simplenews_rules_rules_action_info() {
      $actions = array(
         'custom_simplenews_rules_actions_get_subscribers' => array(
            'label' => t('Get subscribers by Simplenews Newsletters category'),
            'group' => t('Custom'),
            'parameter' => array(
               'category' => array(
                  'type' => 'text',
                  'label' => t('Category'),
                  'options list' => 'custom_simplenews_rules_options_list',
                  'description' => t('Specify category to select users from'),
               ),
            ),
            'provides' => array(
               'entity_fetched' => array('type' => 'list', 'label' => t('Fetched entity')),
            ),
         ),
      );

      return $actions;
   }

   function custom_simplenews_rules_options_list() {
      $taxonomy_vids_objects = db_query("SELECT vid FROM {taxonomy_vocabulary} WHERE module = :module", array(':module' => 'simplenews'))->fetchAll();

      $taxonomy_vids_array = array();
      foreach ($taxonomy_vids_objects as $value) {
         $taxonomy_vids_array[$value->vid] = $value->vid;
      }

      $taxonomy_vids = implode(',', $taxonomy_vids_array);
      $taxonomy_tids = db_query("SELECT tid, name FROM {taxonomy_term_data} WHERE vid IN (:vids)", array(':vids' => $taxonomy_vids))->fetchAll();

      $categories = array();
      foreach ($taxonomy_tids as $value) {
         $categories[$value->tid] = $value->name;
      }

      return $categories;
   }

   function custom_simplenews_rules_actions_get_subscribers(&$category) {
      $categories_array = array();
      foreach ($category as $key => $value) {
         $categories_array[$key] = $key;
      }

      $categories = implode(',', $categories_array);
      $subscribers_snids = db_query("SELECT snid FROM {simplenews_subscription} WHERE vid IN (:vid)", array(':vid' => array_keys($categories)))->fetchAll();

      $subscribers_uids = array();
      foreach ($subscribers_snids as $value) {
         $subscribers_uids[$value->snid] = db_query("SELECT uid FROM {simplenews_subscriber} WHERE snid = :snid AND activated = 1", array(':snid' => $value->snid))->fetchAll();
      }

      $users_list = entity_load('user', $subscribers_uids);

      return array('entity_fetched' => array_values($users_list));
   }

```

Can not determine what I've done wrong. Please help!

# Answer
From the very beginning, I went the wrong way. The problem is solved with the vievs\_rules module. I made a view of simplenews subscribers, with relations with subscriber:email and subscription:category, then added filters by term (subscription category), by user (active or not) and subscription status. I used a user entity as resulting variable. Then I just imported the view into views loop (Rules UI) and voila!

Very thanks to @Pierre.Vriens for pointing me to views\_rules
> 1 votes

---
Tags: 7, rules, emails
---


title: How do I export calendar?

text:
# Question
Title: How do I export calendar?
I am using the calendar module and I have added many events to it like a timetable.

How can I export these events as an excel format? So that I can see the whole calendar events in the excel file when I need.

Thank you in advance.

# Answer
You can also create a view of calendar event data and export data in excel format by the help of view\_data\_export
> 0 votes

---
Tags: views, 8, datetime
---