# Question
Title: How to redirect all variations of a domain to https version?
Google has started punishing non https sites both in SEO and their browsers. So I guess we must make sure that all our clients are using https

Assuming that I have a domain example.com I would like to redirect all the variations of this domain to the https version.

There can be six variations `example.com`, `www.example.com`, `http://example.com`, `http://www.example.com`, `https://example.com`, `https://www.example.com`.

I want to make sure that all these variations redirect to `https://www.example.com`.

# Answer
example.com is the naked version of www.example.com. In the settings for the domain, add an A name pointing to IP of your server.

Add a C Name that points to the www version at the same IP.

If you are running Apache, in the virtual host settings add both Servername and ServerAlias.

```
<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com

```

This will make sure that your server listens both the naked domain and normal domains and points them to you code folder for execution.

Make sure the .htaccess file contains the following lines.

```
  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]

```

This code just sets a flag called protossl, if you have visited using https. This will ensure that you don't have infinite redirections between http and https as mentioned in the comments.

Comment out all other settings related to http and https redirection, and add the following lines.

```
#
# Rewrite http(s)://example.com to https://www.example.com
#
RewriteCond "%{HTTP_HOST}" "!^www\." [NC]
RewriteCond "%{HTTP_HOST}" "!^$"
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#
# Rewrite http://www.example.com to https://www.example.com
#
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

This code was provided by https://www.drupal.org/u/mdrescher on https://www.drupal.org/forum/support/post-installation/2018-04-15/forcing-to-https#comment-12723535.

These changes will make sure that all six variations `example.com`, `www.example.com`, `http://example.com`, `http://www.example.com`, `https://example.com`, `https://www.example.com` are redirection `https://www.example.com`
> 2 votes

---
Tags: redirection
---


# Question
Title: Select the right pathauto alias for a node
I'm working on a drupal 8 project, I need to access the content type X nodes via two aliases depending on some conditions, for this I've created two Pathauto patterns using Pathauto contrib module:

```
path_1 --> /local/[node:title]

path_2 --> /global/[node:title]

```

path\_1 & path\_2 are supposed the machine name of those two patterns.

What are those two patterns? actually what I want to do is check if a node of type X has the checkbox field 'global' checked so use `/global/[node:title]` as alias for this node else use `/local/[node:title]`.

Which hook should I implements for selecting/altering a pathauto pattern for a node? And can I use those aliases as a route for a controller?

# Answer
> 2 votes
Another option, and I find this to be preferable to altering the token because it's exposed to site builders and makes what's happening perfectly clear in the UI, is to create your own custom token that will return `/global` or `/local` for that piece of the url. You just need to implement `hook_token_info` and `hook_tokens`. This blog post walks you through the process.

Ex:

```
/**
 * Implements hook_token_info().
 */
function MY_MODULE_token_info() {
  $info['tokens']['node']['MY_TOKEN_ID'] = [
    'name' => t('MY TOKEN LABEL'),
    'description' => t('Return "/global" for nodes with the global checkbox checked, otherwise returns "/local".'),
    'type' => 'url-fragment',
  ];
  return $info;
}

/**
 * Implements hook_tokens().
 */
function MY_MODULE_tokens($type, $tokens, array $data, array $options, Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ($type == 'node' && !empty($data['node']) && isset($tokens['MY_TOKEN_ID'])) {
    $node = $data['node'];
    $global_or_local = '/local';
    if ($node->hasField('MY_GLOBAL_FIELD') && !empty($node->MY_GLOBAL_FIELD->value)) {
      $global_or_local = '/global';
    }
    $replacements['[node:MY_TOKEN_ID]'] = $global_or_local;
  }
  return $replacements;
}

```

Note: I'm not sure if that logic to determine global or local is perfect, but it should be close.

# Answer
> 0 votes
Try with `hook_pathauto_pattern_alter` something like:

```

/**
 * Implements hook_pathauto_pattern_alter().
 */
function your_module_pathauto_pattern_alter(\Drupal\pathauto\PathautoPatternInterface &$pattern, array $context){
    /* @var $node Drupal\node\Entity\Node */
    //- If you want it just on update operation add $context['op'] == 'update' condition
    if ($context['module'] !== 'node' || !($node = $context['data']['node']) || $node->bundle() !== 'type_X') {
        if ($node->global) {
            $pattern->setPattern('global/[node:title]');
        }else{
             $pattern->setPattern('local/[node:title]');
        }
    }
}

```

---
Tags: 8, path-aliases
---


# Question
Title: How to use Views Excel Export or Views data export to export a filtered table?
A while back I asked a question about how to pass a list of columns to display in a views table and a solution closest to what I wanted to do was a module:

Views Dynamic Fields

I was positively shocked that the description of the project mentioned the second part of what I need to do here. Export that view to an Excel spreadsheet.

> This module provides additional advantages when used with the Views Bonus Pack module or the Views Excel Export module to generate an xls file from a view. The xls file will only display the fields you have chosen on the rendered view instance in browser.

I need to let the user choose the columns, then render the view with those columns and expose filters for all chosen columns, apply them, then download the result in an excel file. Unfortunately I was not able to find a description how do I actually do that. Using the xls feed option I don't get any fields from the view itself (seems like I need to add the fields manually again) which I can't imagine works with the filters from the view itself. Exporting the file works, but it only shows the default "Title" field (without adding fields to the feed manually).

I had the same problems with Views data export, creating a new data export started with a default "Title" field and I don't think you're supposed to add the same filters again.

Let me know if you have any experience with those modules or ever had to export a view to a spreadsheet.

# Answer
I just used Views Data Export module for a Drupal 7 project.

1. Create a view with the configuration you require (exposed filters, etc.).
2. Add a new display to your view of the type "**data export**". (As you duplicate your display the filters should inherit, but otherwise, you just want the "**main**" view and the "**data export**" view configured the same.)
3. In the "Page Settings" of the "**data export**" view display, give it a unique path (This is true even for tabbed items like admin views linked in admin menus).
4. In the "Page Settings" of the "**main**" view display, attach the "**data export**" display (This will provide a little CSV link at the bottom of your view).
5. Under the "**Format**" settings for your view, make sure you select CSV. Then edit settings and check the box for "download as file" or whatever it is.

Now, clicking on that CSV icon that appears at the bottom of your view page/block will export a CSV file that will inherit the filtered table. Just ensure the exposed filters match in each display.
> 1 votes

# Answer
Another module you should have a look at for addressing these requirements is Forena. You would use it's report writing features (such as its WYSIWYG report writer and/or it's query builder) to first create a report that fits your needs (think of it as the equivalent of creating a view). The result of it could be a tabular output and/or graph. After the report content matches the specifications, you could save it as (e.g.) a XLS file. The Forena Video demos and tutorials contain quite some links to live demos.

Any report created with Forena can be exported to various file formats, such as CSV (or XLS). To do so, just add `.csv` (or `.xls`) as an extension to the report (output) URL. That contains the CSV (or XLS) equivalent of that report. As a sample, consider the sample report located at `/reports/sample.states` (in your own site, one of the samples shipped with Forena). Change the URL to `/reports/sample.states.xls` (= just add `.xls` to it) to get the same report in `.xls` format. If you'd add such `.xls` to the URL of the Simple Table of States in the demo site, the result is like so ... Same technique applies for other supported extensions (export formats), such as adding `.html`, `.pdf` or `.doc` (MS Word).

Forena's equivalent of "*Views exposed filters*" (as in your question) is what is called "*Report parameters*". Have a look at the sample report "Report that filters based on state lookup" for an online example of that. By default (if you don't specify a report parameter), the sample shows a report for state "Washington". Use the `Parameters` link to specify any other value (= another state), and note how the report title and report content changes.

On top of that, all *data blocks* are accessible directly via their url also, provided you have permission to access that block. Here are a few samples of that, for the sample report located at `/reports/sample.states`:

For short, to answer this specific question I'd write the various (custom) SQLs I need, format it as reports that fit my needs, and then just save it as an XLS (or CSV?).

Disclosure: I'm a co-maintainer of Forena.
> 0 votes

---
Tags: 7, views, log-messages
---


# Question
Title: Programmatically delete pathauto alias pattern?
I know how to remove a pattern via the UI. Is it possible to do this programmatically to be used in hook\_update()?

EDIT: I think asking this answered my question. Will post a followup answer. Probably just entity\_load/entity::delete

# Answer
> 3 votes
Ended up throwing the following into my\_module.install

```
/**
 * Deletes the product_nodes path alias. Check watchdog for error in case of failure.
 */
function my_module_update_8001(){
  $alias_id = 'product_nodes';
  if($alias_entity = Drupal\pathauto\Entity\PathautoPattern::load($alias_id)){
    try{
      $alias_pattern = $alias_entity->getPattern();
      $alias_entity->delete();
      return t('Successfully deleted @id PathAuto pattern. If this was done in error, you can recreate it by using the pattern: @pattern.',
        array(
          '@id'=>$alias_id,
          '@pattern'=> $alias_pattern,
        )
      );
    } catch(Exception $e){
      \Drupal::logger('my_module')->error('Encountered the following error while trying to delete the @id path alias pattern: @error',
        array(
          '@id'=>$alias_id,
          '@error'=>$e->getMessage(),
        )
      );
      return 'Failed to delete @id PathAuto pattern. Check the error log for details.';
    }
  } else {
    return t('No PathAuto pattern found with the ID @id.',
      array(
        '@id'=>$alias_id,
      )
    );
  }
}

```

---
Tags: 8, path-aliases
---


# Question
Title: Related Content By Taxonomy Term and fields
I have a content type which has taxonomy term field (Department). There is another field of the same taxonomy term (Priority Department)

I want to create a list of related content where the block shows only priority department related content and not the department field.

I tried views and contextual filter and relationship with no luck

# Answer
> 0 votes
You don't need to duplicate Taxonomy Vocabulary, one is enough.

You do need to have two Fields referencing the same Taxonomy Vocabulary, one for `Department` categorizing it, and the other for `Select` through which you're controlling what the related content is.

This is still a case of showing sibling nodes but through criteria of matching one field to a different field that just happens to references the same taxonomy.

1. Create Views listing your Organization nodes in a Block Display
2. Add Filter `Select`, set it to your vocabulary and then choose `Is not empty (NOT NULL)`
3. Add a Contextual filter for the Field `Department` and configure it:
`When the filter value is NOT available`
**Provide default value**
**Taxonomy term ID from URL**
**Load default filter from node page, that's good for related taxonomy blocks**
**Filter to items that share any term** `When the filter value IS available or a default is provided`
**Specify validation criteria**
**Taxonomy term ID**
**\[your vocabulary\]**
**One or more IDs separated by , or +**
4. Place your block in a region shown only on Organizations, you will see nodes listed that are tagged with the term that is in the current node Select field.

This solution relies on the concept that you won't have the same terms in Select Field that you have in the Department field.

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


# Question
Title: Is there a way to order by COUNT('column') without returning an integer?
I'm trying to make this query work correctly in Drupal 8. I want to return the events in order of most frequently occurring in the database table (Users vote for the event they prefer). But I only want to display the event name and not the number of times someone has voted. Here is my SQL query:

```
SELECT `event`
    FROM     `eventform`
    GROUP BY `event`
    ORDER BY COUNT(`event`) DESC

```

In SQL pro it returns correctly the following data.

1. Brewery
2. Conference
3. Concert
4. Dinner
5. Musical

With Drupal, I am getting the following data.

1. Brewery
2. 10
3. Conference
4. 8
5. Concert
6. 7
7. Dinner
8. 6
9. Musical
10. 4

How can I make the following code return only the event names?

```
$query = \Drupal::database()->select('eventform', 'm');
$query->fields('m', ['event']);
// It doesn't return the correct order unless I use
$query->addExpression('COUNT(event)', 'count');
$query->groupBy('event');
// I want something like orderBy(COUNT('event'),'DESC'), but this
// returns incorrect ranking;
$query->orderBy('count','DESC');
$votes = $query->execute()->fetchAll();

```

Here is how I'm rendering:

```
 $rankings=array();
  foreach($votes as $key){
    foreach ($key as $value) {
      $rankings[] = $value;
    }
  }

    $build = [
      'rankings' => [
        'rankings_child_element' => [
          '#theme' => 'item_list',
          '#list_type' => 'ol',
          '#items' => $rankings,
        ]
      ],
      '#empty' => t('No votes found'),
    ];
    return $build;

```

} }

# Answer
> 1 votes
Try this :

```

  use Drupal\Core\Database\Database;
  $connection = Database::getConnection();
  $sth = $connection->select('eventform', 'm');
  $sth->addField('m', 'event');
  $sth->addExpression('COUNT(m.event)', 'count');
  $sth->groupBy('m.event');
  $sth->orderBy('count','DESC');
  //- Execute the statement
  $data = $sth->execute();
  //- Get all the results
  $results = $data->fetchAll(PDO::FETCH_ASSOC);

```

you will get the `$results` as an array something like:

```

array:5 [▼
   0 => array:2 [▼
     "event" => "Brewery"
     "count" => "10"
   ]
   1 => array:2 [▼
     "event" => "Conference"
     "count" => "8"
   ]
   2 => array:2 [▼
     "event" => "Concert"
     "count" => "7"
   ]
   3 => array:2 [▼
     "event" => "Dinner"
     "count" => "6"
   ]
   4 => array:2 [▼
     "event" => "Musical"
     "count" => "4"
   ]
 ]

```

if you want to get only the `event name` loop thought the `$results` something like :

```

 $events_name = [];
 foreach ($results as $result){
    $events_name[] = $result['event'];
  }

```

---
Tags: 8
---


title: hook_apachesolr_exclude not working

text:
# Question
Title: hook_apachesolr_exclude not working
I am using hook\_apachesolr\_exclude but its not working.I have created a custom field if that field is checked i want to exclude that node I wrote the given below code:

```
function a10_exclude_node_apachesolr_exclude($entity_id, $entity_type, $row, $env_id) {
    $result_node = node_load( $entity_id );
    if( isset( $result_node->field_exclude_from_search['und'][0]['value'] ) and $result_node->field_exclude_from_search['und'][0]['value'] == 1 ){
        return TRUE;
    }
    return FALSE;
}

```

even when i am writing die inside the hook, hook is not invoking.Please let me know how i can check the above hook is invoking or working.I have also tried the Apache Solr Node Exclude module, when i am checking the node to exclude it does not come inside the result but when again i uncheck the node same result come there and when i uncheck the two or more nodes they do not exclude from search result.

# Answer
> 1 votes
I have fixed the problem to exclude node from Apache Solr search by installing Apache Solr Exclude Node module. To configure this module, please follow the below steps:

1. Enable excluding of nodes in the submission form settings fieldset in the content type settings (e.g. admin/structure/types/page).
2. Find the vertical tabs fieldset "Apache Solr exclude" in the node edit form.

Check "Exclude from Apache Solr" and save.

---
Tags: hooks, search
---


# Question
Title: How can I add multiple conditions for the same field taxonomy term in views query?
I make some query for views filter for nodes. Use in hook\_views\_query\_alter.

```
$definition = [
   'table' => 'node__field_characs',
   'field' => 'field_characs_target_id',
   'left_table' => 'taxonomy_index',
   'left_field' => 'tid',
   'operator' => '='
];
$join = \Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
$rel = $query->addRelationship('node__field_characs', $join, 'taxonomy_index');
$query->addTable('node__field_characs', $rel, $join, 'node__field_characs');

```

I add array of conditions.

```
$q_and = db_and();
foreach($ch_id as $key => $val_array){
   $q_and->condition('node__field_characs.field_characs_target_id', $val_array, 'IN');
}
$query->addWhere(0, $q_and);

```

But if array $ch\_id have more then 1 elements, it works wrong. It does not show any nodes.

A similar problem is described here Perform a query with an entity field condition with multiple values. But how can this be applied in this case?

# Answer
> 0 votes
you try this code:

```
$and = $query->andConditionGroup();
foreach($ch_id as $key => $val_array){
   $and->condition('node__field_characs.field_characs_target_id', $val_array, 'IN');
}

$query->condition($and);

```

---
Tags: views, 8, database
---


# Question
Title: How can I run client side validation before a Drupal AJAX submit call?
I'm trying to perform client side validation using jquery.validate.js on a form submitted via Ajax (using form actions), but for some reason, the client side validation is not being triggered.

This is what I have in my template.php file in order to trigger an ajax call for login:

```
$form['actions']['submit']['#ajax'] = array(
    'callback' => 'fantasia_user_login_ajax_callback',
'wrapper' => 'user-login-form',
    'event' => 'mousedown',
 );

```

And here's my js to trigger the client side validation:

```
(function ($) {
Drupal.loginAjax = {
    form_id: 'user-login-form'
};
Drupal.behaviors.loginAjax = {
    attach: function (context ,settings) {
         Drupal.loginAjax.beforeSubmit = function (form_values, form, options) {
                $("form#user-login-form", context).validate({
                    rules: {
                        edit_pass: "required",
                        edit_name: "required"
                    },
                    messages: {
                        edit_name: {
                            required: "E-mail Address is required"
                        }
                    }
                });
        }

        for (ajax_el in settings.ajax) {
            if (Drupal.ajax[ajax_el].element.form) {
                if (Drupal.ajax[ajax_el].element.form.id == Drupal.loginAjax.form_id) {
                    Drupal.ajax[ajax_el].beforeSubmit = Drupal.loginAjax.beforeSubmit;
                }
            }
        }

    }
};
})(jQuery);

```

The beforeSubmit method is being triggered because when I print to the console, I do get a value.

On a sidenote, I've tried doing this using the beforeSend instead. The client side validation does trigger, but the submit is not being halted.

Any pointers please?

# Answer
I would attempt to hijack the submit form by changing the event type and triggering the submission yourself.

For example:

```
$form['actions']['submit']['#ajax'] = array(
    'callback' => 'fantasia_user_login_ajax_callback',
'wrapper' => 'user-login-form',
    'event' => 'submitmyform',
 );

```

Then just add your own click or form handler. Once you happy with the validation simply trigger the event "submitmyform". For example:

```
Drupal.behaviors.loginAjax = {
  attach: function (context ,settings) {
    // Cache the form object
    var $form = $("form#user-login-form", context);
    var $submitButton = $('input[type="submit"]', $form);

    // Use once so we dont attach submit multiple times
    // Use off to remove any existing submit handler
    $form
      .once('loginAjax')
      .off('submit')
      .on('submit', function(e){
      e.preventDefault();
      var $form = $(this);

      // Run validation on $form object.

      // If success, trigger event on button
      if(valid) {
        $submitButton.trigger('submitmyform');
      }
    });
  }
}

```

I have not tested this code but in essence this is how I recommend you approach it rather than messing around with the ajax object itself.
> 4 votes

# Answer
This is stupid but it works, just add `'event=>'onsubmit'`. It will fix a problem with the jQuery event priority in drupal code.

```
$form['actions']['submit']['#ajax'] = array(
    'callback' => 'fantasia_user_login_ajax_callback',
    'wrapper' => 'user-login-form',
    'event' => 'onsubmit',
 );

```
> 1 votes

---
Tags: 7, ajax, javascript
---


title: Create translated node programmatically

text:
# Question
Title: Create translated node programmatically
I need to recreate the behavior drupal has when you create a translation but programmatically.

Doing `$node->addTranslation('de');` on a hook insert create an empty node but I need the field to be filled with the untranslated node content.

Is there a way to achieve this instead of having to repopulate every field from the main node ?

# Answer
> 5 votes
`addTranslation` takes a second parameter, `$values`:

> An array of initial values to be assigned to the translatable fields. Defaults to none.

So in theory you should just need to make use of that parameter, and pass the node's current field values:

```
$node->addTranslation('de', $node->toArray());

```

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


# Question
Title: Custom theme function with drupal render
I'm trying to make a custom module based on menu module to render a sitemap.

I want to use a custom theme function for rendering it but for unknown reasons my variables are not passed to the theme function. Here is my code (simplified so we get what matter) :

```
function custom_module_theme() {
  return array(
    'custom_module_link' => array(
      'variables' => array(
       'attributes' => NULL,
       'title' => NULL,
       'href' => NULL,
       'below' => NULL,
       'original_link' => NULL,
      ),
    ),
  );
}

function theme_custom_module_link(array $variables) {
 $element = $variables;
 $output = ...;
 ...
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . "</li>\n";
}

function _custom_module_tree_output($tree) {
    ...
    ...
    // Allow menu-specific theme overrides.
    $element['#theme'] = 'custom_module_link';
    $element['#attributes']['class'] = $class;
    $element['#title'] = $data['link']['link_title'];
    $element['#href'] = $data['link']['link_path'];
    $element['#original_link'] = $data['link'];
  }
 return $element;
}

function custom_module_page() {
  $tree = ...
  $output = _custom_module_tree_output($tree);

  return drupal_render($output);
}

```

This code return a error page with the following : TypeError: Argument 1 passed to drupal\_attributes() must be of the type array, null given ...

I don't understand why drupal\_render doesn't iterate over the $element\['#theme'\] call to fetch variables as described in the documentation. What I'm missing ?

> From the doc : Basically, the '#theme' = 'function\_name' calls theme\_function\_name(), and other array values of the form '#var\_name' = $value in the same array are passed as arguments to the theme function

If I dpm $variables in my theme\_custom\_module\_link function, variables are set as NULL as in my hook\_theme ...

# Answer
What I wanted to do is to get the html through a function and not a template. So actually there is no need to set the variables, just the 'render element' did the trick.

```
function custom_module_theme() {
  return array(
    'custom_module_link' => array(
      'render element' => 'element',
    ),
  );
}

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to show all nodes and comments by a user in a single view?
I am using Drupal 8 in combination with the Forum module, and I'd like to show all comments and nodes by a user on his profile page, in a single view.

I can't find a way to get this to work, because they are different entity types.

I've tried using two relationships, but that only gives me rows with each comment linked to each node.

Is this at all possible?

EDIT: This is an example of the result that I'm trying to achieve:

* Comment 5
* Comment 4
* Node 2
* Comment 3
* Node 1
* Comment 2
* Comment 1

# Answer
This is an example of my setup, just switch out *article* or *content type* for your *content type* or *forum posts*.

**node--article--teaser.html.twig:**

```
<div class="{{ node.type.0.target_id | clean_class }}-teaser-wrapper" {{ attributes }}>

    {# other fields #}

    {{ content.field_comments }}

</div>

```

or:

```
<div class="{{ node.type.0.target_id | clean_class }}-teaser-wrapper" {{ attributes }}>

    {{ content }}

</div>

```

As long as the comment field is set to display in your teaser *view mode*, and printed via your template, the comments will show in the view results.

**View Config:**

The contextual filter is the important part.

This setup uses content format teaser, the alternative would be using fields. Both will work, with fields you may need a relationship to comments depending on what fields you need available in your view.
> 0 votes

---
Tags: views
---


# Question
Title: How to obtain the machine name and field type of the fields of a content type filtered by those created by the user?
I have a content type News to which I added the following fields:

```
Label | System Name | Type
Image | field_image | Is a image
Related content | field_related_content | is a Paragraph
Date | field_date | Is Datetime type

```

What I'm trying to do with a custom module is, I want to get the machine names of each field and the type of field that I defined.

Is it possible to obtain data from only those that I generated? That is, for example, the created fields, or the update field or those that come by default do not appear, in some way filter the ones that I defined as the user in the content type.

For example, after some form of processing the type of content, only result in:

```
$result = [

  'field_image' => [
     'type' => 'image',
   ],
   'field_related_content' => [
    'type' => 'paragraph' // i don't know if the type is Entity reference revisions in reality
   ],
   'field_date' => [
    'type' => 'datetime'
   ]

];

```

Thanks.

# Answer
If you mean the fields configurable in UI, then you can get them through EntityFieldManager::getFieldDefinitions:

```
$fields = array_filter(
  \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'article'),
  function ($fieldDefinition) {
    return $fieldDefinition instanceof \Drupal\field\FieldConfigInterface;
  }
);

$result = [];
foreach ($fields as $key => $definition) {
  $result[$key] = [
    'type' => $definition->getType(),
  ];
  // if the field is a reference field get also the target entity type
  if (in_array($result[$key]['type'], ['entity_reference', 'entity_reference_revisions'])) {
    $result[$key]['target_type'] = $definition->getSettings()['target_type'];
  }
}

```

Entities have base fields defined in code and bundle fields defined in configuration. Drupal doesn't keep track whether a bundle field is configured by you or is from another source. A field can be pre-installed by a module, then deleted and added in UI again and Drupal wouldn't be able to tell the difference.
> 0 votes

---
Tags: 8
---


title: Previous month in sql

text:
# Question
Title: Previous month in sql
I have sql, where I need to select data for this month and data for previous month. How to do extraction od previous month data?

In my block in `build()` functionI have this:

```
//...
if ($what == "en_flip_per_month"){

    list($m, $y) = statistics_data_for_block('monthname', 'year');

    $sql = $connection->select('node_field_data', 'nfd');
    $sql->addExpression('COUNT(nfd.nid)', 'counting');
    $sql->where("nfd.langcode='en'");
    $sql->where("FROM_UNIXTIME(nfd.created, '%M' ) = ".$m."");
    $sql->where("FROM_UNIXTIME(nfd.created, '%Y' ) = ".$y."");
    $sql->groupBy('nfd.langcode');
    $sql->orderBy('nfd.created', 'DESC');
}
//....

```

and in my .module file I have this:

```
function statistics_data_for_block($m='', $y=''){
    $month = '';
    $year = '';

    //current
    if ($m == "month"){
        $month = "MONTH(CURRENT_TIMESTAMP)";
    }
    if ($m == "monthname"){
        $month = "MONTHNAME(CURRENT_TIMESTAMP)";
    }

    if ($y == 'year'){
        $year = "YEAR(CURRENT_TIMESTAMP)";
    }

    //... SOMETHING FOR PREVIOUS MONTH ...

    return array($month, $year);
}

```

So, I need a way to extract `MONTH`, `MONTHNAME` and `YEAR` of `(CURRENT_TIMESTAMP - 1 month)`.

There was this one solution - use of `SET` and `DECLARE`, but how can it be done in Drupal 8 dynamic query?

Thanks

# Answer
I did it! Answer is pretty clever - just take first day of current month and subtract 15 minutes.

```
//PREVIOUS MONTH

//"month"
    $month = "MONTH(DATE_SUB(DATE_FORMAT(CURRENT_TIMESTAMP ,'%Y-%m-01'), INTERVAL 15 MINUTE))";
}

//"monthname"
    $month = "MONTHNAME(DATE_SUB(DATE_FORMAT(CURRENT_TIMESTAMP ,'%Y-%m-01'), INTERVAL 15 MINUTE))";
}

//'year'
    $year = "YEAR(DATE_SUB(DATE_FORMAT(CURRENT_TIMESTAMP ,'%Y-%m-01'), INTERVAL 15 MINUTE))";
}

```
> 0 votes

# Answer
Not really related to Drupal, but this works on mySQL

```
MONTH(NOW() - INTERVAL 1 MONTH)
MONTHNAME(NOW() - INTERVAL 1 MONTH)
YEAR(NOW() - INTERVAL 1 MONTH)

```
> 0 votes

---
Tags: database
---


title: Possible to have conditional Tokens?

text:
# Question
Title: Possible to have conditional Tokens?
In using URL aliases, is there a way to have conditional token usage? An example of what I'm looking for is:

* I have programs on my page, each having their own unique program code.
    + By default, say my program is General Arts, the URL alias would be */programs/general-arts*
* However, sometimes, the programs may have multiple program codes due to being taught in different locations.
    + What I'd like (if it's possible at all) is when I create another program with the same name (let's use General Arts again for example), except it has a different program code, I'd like the URL alias' to then be */programs/general-arts-C123* for the first one and */programs/general-arts-D321* for the second one because they're the same program, just different program codes (due to being taught in different locations). Pretty much appending the course code to the end of the URL to distinguish the two.

Or is the only way to do something like this is to manually override the URL alias and put the custom URL in?

# Answer
> 1 votes
You can just return an empty string with your custom token.

Or you could make your custom token return the title and course code and handle it that way.

---
Tags: 8, nodes, tokens
---


title: Change Hyperlink Color in Views

text:
# Question
Title: Change Hyperlink Color in Views
I am looking for a way to change the hyperlink for Node title on a view. So far have tried rewriting the Node title field and also tried a global text field but links still show as blue.

Tried this but did not work:

`<a href="{{ view content }}" style="color: #cc0000">{{ Node Title }}</a>`

What is the best way to change link color in views?

# Answer
The correct way to style websites is with CSS.

You can use a selector from the existing Views output, or you can assign a special class to your `Content: Title` Field under `Style settings`. You can `Create a CSS class` for the field wrapper or the HTML element.

Then use the class selector in your CSS inside the theme:

```
.my-class a {
  color: #cc0000;
}

```

If you're not creating your own (sub)theme and only want to make minor adjustments you can use the CSS Editor or CSS Injector modules.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to display a vocabulary term list with node count?
How can you display a vocabulary term list with node count?

I have a vocabulary named *books authors*, I want to display a list of the *terms* which includes the total number of nodes next to each term. Like this:

* William Shakespeare (4)
* Xyz (6)

# Answer
You can do this by using the Views module.

1. Create a new View of type Content, filter to all the Content type nodes relevant for your case.
2. Then add a Contextual filter (under `Advanced` in Views) for the Field **Has taxonomy term ID** and configure it to display a Summary:

`When the filter value is NOT available`
**Display a summary**
`Format` **List**
`Base path` (you *must* enter the Page path if this isn't the first Page Display in your Views)
**Display record count with link**
3. If your Taxonomy reference field accepts more than one value (so your nodes can be tagged with more than one term) also check out the options under:

`More`
**Allow multiple values**

You will see a list of tags with the count in brackets. You can click on the terms from the Summary and see the relevant results in a separate page.
> 0 votes

---
Tags: views
---


title: Display a view block on multiple pages

text:
# Question
Title: Display a view block on multiple pages
I have a block that I want to display on `/group/*`. That is working, but it is also displaying the block on `/group/*/edit`which is pretty annoying and unwanted.

Is there a way to restrict that?

# Answer
If you can't list all the groups' paths (if there are too many) you can use an extra module Block Exclude Pages.

Although when it comes to Edit pages it's customary to use the Administration theme for editing content instead of the default theme. This way the blocks meant to be displayed to visitors wouldn't appear when creating/editing content.

You can change this at the bottom of the `Appearance` page: **Use the administration theme when editing or creating content**.

You could also use a lot more complex solution depending on your project needs, like Context or Panels that take over the Blocks layout configuration and allow for a lot more control.
> 1 votes

---
Tags: 8, blocks, group
---


# Question
Title: TypeError: $.ui and $element.dialog is undefined
I have been handed a site to work on. It's on 8.5.1. The site was working. However, I cannot make changes on certain configs. For example, the dialog boxes for the views do not open anymore. I keep getting the following js error under the console.

I do not want to revert the database back to a working condition since the client would lose their data.

Update: The dialog box does work very very random.

# Answer
Thank you everyone for helping. I informed of the senior development of your suggestions. He was able to find the issue. Font Awesome module was installed incorrectly, he also updated to the latest core. We've uninstall Font Awesome and migrated to using Font Awesome CDN.
> 1 votes

---
Tags: 8, javascript
---


# Question
Title: Reassign $view_mode using entity field passed to hook_entity_view_mode_alter()
I'm using **baseFieldDefinitions** to create my custom entity form. With gracious help here, I've been able to successfully generate a radio button on the form which lets the user select what view mode to use for the display.

**Goal**: Get the selected value from the radio button on the form and use it to reset the view mode for the display.

**Problem**: Other than my general confusion, I believe I have a cache issue when invoking the hook to alter the view mode. I'd like to think I was finally able to overcome the array value to single value assignment problems.

I added this code into MY-MODULE.module:

```
/**  * Implements hook_entity_view_mode_alter().  */
function nfl_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
    // Change the view mode to the value selected via radio button on the form.

    if ($entity->getEntityTypeId() == 'nfl_fact'  ) {  /*<-- restrict to custom entity */

        $change_to_view_mode = $entity->change_view->value;  /*<-- get the lowercase value -- not Initial Cap Label  */

        drupal_set_message(sprintf('<pre> change_to_view_mode %s</pre>', print_r($change_to_view_mode, TRUE)));
        drupal_set_message(sprintf('<pre> view_mode before %s</pre>', print_r($view_mode, TRUE)));

        //  $view_mode = $change_to_view_mode;  /*<--- reassign view mode here -didn't work*/
        $entity->view_mode[LANGUAGE_NONE][0]['value'] = $val[0]->change_to_view_mode;  /* <-- reassign */
        $entity->save();

        drupal_set_message(sprintf('<pre> view_mode after reassignment %s</pre>', print_r($view_mode, TRUE)));
    }
}

```

I added some `drupal_set_message` entries to reassure myself that I was getting the variable values changed.

```
<pre> change_to_view_mode standard</pre>
<pre> view_mode before full</pre>
<pre> view_mode after reassignment standard</pre>
Cache cleared.

```

When I click on my link from the viewlist builder, I don't get the display. I get White Screen of Death with the error in the PHP log:

(first few lines)

```
[29-Sep-2018 02:15:53 UTC] TypeError: Argument 1 passed to Drupal\Core\Form\OptGroup::flattenOptions() must be of the type array, null given,
    called in C:\wamp\www\drupal8\web\core\modules\options\src\Plugin\Field\FieldFormatter\OptionsDefaultFormatter.php on line 40
    in C:\wamp\www\drupal8\web\core\lib\Drupal\Core\Form\OptGroup.php on line 23
#0 C:\wamp\www\drupal8\web\core\modules\options\src\Plugin\Field\FieldFormatter\OptionsDefaultFormatter.php(40): Drupal\Core\Form\OptGroup::flattenOptions(NULL)
#1 C:\wamp\www\drupal8\web\core\lib\Drupal\Core\Field\FormatterBase.php(80): Drupal\options\Plugin\Field\FieldFormatter\OptionsDefaultFormatter->v

```

I'm confused. Also am open to guidance on how to better format this question if it looks too goofy ;)

# Answer
I'm not sure exactly what's going on here, but looking at the documentation for hook\_view\_mode\_alter, it looks like you're not resetting the view mode properly. It looks like you need to set it like:

```
/**
 * Implements hook_entity_view_mode_alter().
 */
function nfl_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  // Change the view mode to the value selected via radio button on the form.
  if ($entity->getEntityTypeId() == 'nfl_fact' ) {
    $view_mode = $entity->change_view->value;
  }
}

```
> 0 votes

---
Tags: hooks, caching
---


# Question
Title: Migration from csv problem (Incorrect string value: '\xAB Nove...')
In my drupal 8 project, I'm trying to import data of a content type from a csv file, everything is well, but when I'm trying to execute the migration command `drush mim my_migration` I got the following error:

```
PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xAB Nove...' for column 'sourceid1' at row 1 in                   [error]
/Users/brahim/Sites/news8/core/lib/Drupal/Core/Database/Statement.php:59

```

It seems like a problem of database encoding.. but I don't know what is it really, any idea about the solution?

# Answer
> 1 votes
maybe related to the source file encoding format (try with UTF-8). Check also for string issues (special characters) on the source file.

---
Tags: 8, migrations
---


title: Import test data to theme?

text:
# Question
Title: Import test data to theme?
I'm quite new to Drupal, and I'm still in learning process. I've installed a pure Drupal 8, and installed a the YG Agency theme. Right now the theme is only blank. Is it possible to load some test data into the theme, as it is displayed in the Demo?

http://demo.drupalfreethemes.com/drupal/free-themes/yg\_agency/

I know this can be done is many WordPress themes? Does Drupal support importing test data to themes as well?

# Answer
> 1 votes
The YG Agency theme has a link to the prepopulated database from the following page:

https://www.drupal.org/project/yg\_agency

Just click on the link that says "Download Demo Site".

You can then import the database into MySQL or the like.

---
Tags: 8
---


# Question
Title: <link rel="canonical" href="/relative/url" />
Drupal 8 creates `<link rel="canonical" href="/relative/url" />` by default. support.google.com says:

> Use absolute paths rather than relative paths with the rel="canonical" link element.
>
> Use this structure: https://www.example.com/dresses/green/greendresss.html Not this structure: /dresses/green/greendress.html

I used the Google Search Console URL Inspection and found Google does not recognize relative urls as canonical. It says:

> User-declared canonical N/A

I believe this is causing some indexing problems for our multiple language website. How can we convert the canonical urls to absolute as recommended by Google?

# Answer
The following function updates the rel tags in the head section of all pages on a website. The "revision" and "shortlink" tags are deleted using unset(). The "canonical" tag is converted from a relative to an absolute url. This function should be called from modulename\_preprocess\_html() of your custom module.

```
function canonical_shortlink_revision(&$variables) {

  foreach($variables['page']['content']['system_main']['#attached']['html_head_link'] as $key => $value) {

    if( ($value[0]["rel"] === "revision") || ($value[0]["rel"] === "shortlink") )
      unset($variables['page']['content']['system_main']['#attached']['html_head_link'][$key]);

    if($value[0]["rel"] === "canonical") {
      $href = $variables['page']['content']['system_main']['#attached']['html_head_link'][$key][0]["href"];
      $href = \Drupal::request()->getSchemeAndHttpHost() . $href;
      $variables['page']['content']['system_main']['#attached']['html_head_link'][$key][0]["href"] = $href;
    }

  }
}

```
> 2 votes

# Answer
The metatag module gives you the ability to overwrite the 'canonical' metatag:

* On the module's settings page (`/admin/config/search/metatag`)
* Edit the `General` type
* Under `Advanced` you'll find the **Canonical** field
* Set the field's value to `[current-page:url:absolute]`
* Save

That should do it. The instructions above are for Drupal 8.

**Update 1:**

If you are comfortable using hooks and working with PHP you may also use a theme hook (`hook_page_attachments_alter`) to achieve the same thing. Here's the api spec on drupal.org for the function.
> 3 votes

---
Tags: 8, google-search-console
---


# Question
Title: WYSIWYG CKEditor is altering source text on reload. Why?
I created a paragraph with a text field that uses CKEditor text editor with Full HTML enabled. I switched to the `Source` view and pasted the following code into CKEditor.

```
<!doctype html><html lang="en">
<head>
    <meta charset="utf-8"><title>The HTML5 Herald</title>
    <meta name="description" content="TheHTML5Herald">
    <meta name="author" content="SitePoint">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head><body>
    <script  src="https://code.jquery.com/jquery-2.2.4.min.js"  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="  crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</body></html>

```

Very simple, I was just testing to see if it accepted `script` and `link` tags out of the box. After I saved the page and went back to edit it, the source view only showed:

```
<meta charset="utf-8">
<title></title>
<meta name="description" content="TheHTML5Herald"><meta name="author" content="SitePoint">
<link href="https: //stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" /><script  src="https: //code.jquery.com/jquery-2.2.4.min.js"  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="  crossorigin="anonymous"></script><script src="https: //stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

```

Note that it removed the `doctype`, `html` and `body` tags. What's weird is that in the database, the value for this field in this node is still exactly what I pasted in (with all the tags). Is there a hook or filter that is altering this before it is rendered? How can I prevent this to make sure it always displays what I previously pasted in?

I'm using Drupal 8 and the CKEditor version is 4.7.2 according to the JavaScript console.

# Answer
> WYSIWYG CKEditor is altering source text on reload. Why?

Simply because it makes no sense to print them. I'm sure they added this as a preventative measure to prevent people from writing bad HTML. There is no way to turn this off, for your own good, lol.

If you look at html.html.twig template file, where your CKeditor code will render is already inside the `<body>` tag, so it makes no sense to re-declare the `<html>` nor `<head>` nor `<body>` tags when they already have been declared.

```
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
  </head>
  <body{{ attributes }}>
    {#
      Keyboard navigation/accessibility link to main content section in
      page.html.twig.
    #}
    <a href="#main-content" class="visually-hidden focusable">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}  <--- YOUR CKEDITOR CODE WILL PRINT HERE...
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>

```

---

> `<script src="https://code.jquery.com/jquery-2.2.4.min.js"
>  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
>  crossorigin="anonymous"></script>`

For starters, Drupal 8 comes with jQuery, there is no need to add it, simply you just need to mark it as a dependency to your js file and then and only then, Drupal will load it. See How to include jQuery Once on your Drupal 8 pages

## Loading scripts via CKeditor is considered bad practice. So the question becomes, how can I properly add the .css and .js bootstrap file?

### Option A

Create a library file for your theme if it doesn't have one already

**mytheme.libraries.yml**

```
bootstrap4_cdn:
  css:
    theme:
      https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css: { type: external, minified: true }
  js:
    https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js: { type: external, minified: true }
  dependencies:
    - core/jquery
    - core/jquery.once

```

**Note:** In .yml files spacing matters, so make sure the indentation is exactly the same.

Then on your **theme.info** file add

```
libraries:
  - mytheme/bootstrap4_cdn

```

For better understanding, I encourage you to read Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

---

### Option B

Use the bootstrap library module, which will add the library for you. (Basically does option A for you)

---

### Option C (better yet)

If you want to create a Drupal 8 boostrap 4 theme, then you could create a Drupal Subtheme and use Bootstrap Barrio as your base theme.

Why a sub theme? Because themes are no different than Drupal Core or Contrib modules, if you hack them directly and then download an update for it, you will lose all your changes.
> 0 votes

---
Tags: 8, wysiwyg
---


# Question
Title: Find all content that has Paragraph Content
Is there any way to find all content that has any value in the field created by Paragraph module?

Looking to find content and move it into the Body field so that:

1. We don't loose the content.
2. We can delete the paragraph module.

# Answer
> 2 votes
For each field in drupal website, drupal creates a table in database with name `ENTITYTYPE__FIELDMACHINENAME`, so if you have applied a field called field\_paragraph to a node type the table will name : `node__field_paragraph`, in that table there is a column called `entity_id` which indicates that data belongs to which entity in your website.

so you simply can write a query to fetch a list of all node having data for an specific field, or if you don't know how to write a query you can explore that table to check them manually.

---
Tags: 8, paragraphs
---


# Question
Title: How do I use and administrative form and save a message?
I followed the instructions on Step by step guide to creating an admin form in Drupal 8.

I typed in a welcome text into the admin form and saved it, but after saving the form was empty again.

I am new to Drupal and php and don't know yet how to debug the code. I can not use Php-Storm because it is too expensive. Therefore I am using Visual Studio.

The website and database are running inside Docker. I mounted the folder for the modules, so I can write the module code from outside docker. I am working on a Ubuntu 18.04 machine.

This is the whole class:

```
namespace Drupal\welcome\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class MessagesForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'welcome.adminsettings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormID() {
    return 'welcome_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('hello_world.adminsettings');

    $form['welcome_message'] = [
      '#type'          => 'textarea',
      '#title'         => $this->t('Willkommens Nachricht'),
      '#description'   => $this->t('Willkommens Nachricht, die beim Anmelden erscheint.'),
      '#default_value' => $config->get('welcome_message'),
    ];

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    $this->config('welcome.adminsettings')
      ->set('welcome_message', $form_state->getValue('welcome_message'))
      ->save();
  }
}

```

I just learned how to inpect variables with ksm() and found that the value is stored in the welcome\_message variable.

# Answer
Yes, I found the bug.

In buildForm is says:

```
hello_world.adminsettings

```

But it must be:

```
 welcome.adminsettings

```
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Get all nodes where date field matches month and year
I have a content type with a date field (*myFieldDate*) whose values are timestamps. (I'm collecting only day, month, and year.)

I have a custom form where I have a select list to select month and year. I need to use the `EntityFieldQuery` class to get all the nodes where the date field contains the month and the year I specified.

```
$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'horas')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_day', 'value', $myFieldDate, '=');

```

If the select list contains `'2015-05'`, for example, the query should return all nodes where *myFieldDate* contains a date for that month and year.

# Answer
> 2 votes
You can use a range like condition:

```
$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'horas')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_day', 'value', $myFieldDate . '-01', '>=')
  ->fieldCondition('field_day', 'value', $myFieldDate . '-31', '<=');

```

---
Tags: entities, database, datetime
---


# Question
Title: How to show different delta of a multi-value token?
I have a multi-value field for user statistics (around 18 INT values): the field field\_nurse\_patients contains 18 integers 0,5,3,3...

Is there a way to get a format like below with tokens? Maybe with the token custom module or programmatically?

Desired output:

points: 0 height: 5 weight: 3

I've tried accessing the individual values like

```
[current-user:field_nurse_patients:0]
[current-user:field_nurse_patients:0:value]
[current-user:field_nurse_patients:value:0]
[current-user:field_nurse_patients:und:0:value]

```

None of which allows me to target the individual deltas.

There are a couple of similar (older) questions, but none of them really answers it.

Tokens for multi-valued fields?

What is the correct token for a multi value field?

# Answer
> 1 votes
You can get to the delta values of multi-value fields with the help of Compound token (it doesn't have to be a compound token, it can be something like `[node:field_test:und:1:value]`).

As you've already figured out you need Token filter to evaluate tokens in Textarea fields, such as Views Headers or Footers.

---
Tags: 7, tokens
---


# Question
Title: Statistics module not logging content views after upgrade
I recently upgraded my news blog from 8.4.0 to 8.6.1 and the major issue I have is that the statistics module is not logging the content views any more. The old articles seem to have stack in the same count number and the new articles not showing up in teaser links as they are stuck to zero.

Any ideas please?

# Answer
There was a problem with missing php file in theme folder and that caused the issue. When we added the file then the counter worked as expected.
> 0 votes

---
Tags: nodes
---


# Question
Title: How can I assign a database for each user?
I am new to Drupal and facing problems. I want to assign a database for each user where user can edit, delete or make entry to their database table.

For example I want to develop a database management system for doctors so that each doctor has their own patient database with scanned image of report, patient name, address, description, sex etc so that they can keep track of their patients. How can I implement it in Drupal 8?

# Answer
> 1 votes
You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

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).

With the appropriate permissions configured, 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. Refer to "How to create collections of content that can be accessed by users with various access levels?" for more info about all this.

**Resources**

---
Tags: 8, database
---


# Question
Title: View to show 2 different fields that have multiple values next to each other
I have a content type that has 2 fields on it:

* image (multiple values)
* image description (multiple values)

I have 6 images and 6 descriptions. I want to use a view to show each image with each description. I have tried playing around with the "Display all values in the same row" settings but just can't get this to work. It displays the same image repeatedly (6 times) and then the descriptions are all correct, then repeats the next image 6 times again.

I am tearing my hair out here, how do I get a view to simply out output:

Image 1, Description 1 Image 2, Description 2

and so on?

I have included an image of current output plus the way the fields were set up on the node. I have set them up this way as I need to import a lot of them.

# Answer
As already suggested the most sensible way would be to use the Alt text field for each Field value. You can still import the images with matching textual descriptions into a Single field with multiple images (each image with its own description).

But there is fix you can use if you want to keep the structure - "manually" add all the relevant information to display in Views results.

Multiple value Fields have `delta` info that records the order/placement of each value.

As you know in Views these types of Fields have Multiple field settings where you can `Display all values in the same row`.

This is what you want to do here, but only display one value at a time. First add the File field showing the **first** image only, then add Description field showing the **first** description only, then add File field *again* showing the **second** image, then add the Description field *again* showing the **second** description only and so on until you've shown all of them:

First image and Description:

> **File:** Display **1** value(s) starting from **0** (first item is 0)
> **Description:** Display **1** value(s) starting from **0** (first item is 0)

Second image and Description:

> **File:** Display **1** value(s) starting from **1** (first item is 0)
> **Description:** Display **1** value(s) starting from **1** (first item is 0)

Third image and Description:

> **File:** Display **1** value(s) starting from **2** (first item is 0)
> **Description:** Display **1** value(s) starting from **2** (first item is 0)

etc...
> 0 votes

# Answer
As commented there might be better data models. But in case you can't change the data model it's probably the easiest solution to switch the View to display content in a view mode and display the field deltas in a node template:

*node--content-type--view-mode.html.twig*

```
{% for key, item in content.field_image if key|first != '#' %}

  {{ item }}

  {{ content.field_description[key] }}

{% endfor %}

```
> 0 votes

---
Tags: views
---


# Question
Title: add_where() causes the view not to be displayed
have a page that features a few views based on content types. Each content type includes a keyword field. This page is reached from a short quiz. I'm trying to limit the content in the views based on responses in the quiz by pulling the $\_POST data and comparing it to the keyword field. The code is executing, and I'm fairly sure I have the join right, but instead of limiting the content to matching keywords, the entire display block just disappears.

Here is my module code:

```
<?php

if (!empty($_POST["q1"])) {

    $q1 = $_POST['q1'];
    $q3 = $_POST['q3'];

    /**
     * Implements hook_views_query_alter to add a where clause to the views queries
     */
    function iamru_keyword_filter_views_query_alter(&$view, &$query) {

        global $q1, $q3;

        if ($view->name == 'iamru_prepared_statement') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value', $q1, '=' );
        }

        if ($view->name == 'iamru_word_for_you_view') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value', $q3, '=' );
        }

    }

}

```

Can anyone see where I've gone wrong here?

Interesting update: If I replace $q1 with 'somekeyword' in the add\_where call, it actually works.

# Answer
> 0 votes
It was a problem with accessing the global variables. In the end, I got it working with the following function:

```
function iamru_keyword_filter_views_query_alter(&$view, &$query) {

        $q1 = $GLOBALS["_POST"]["q1"];
        $q3 = $GLOBALS["_POST"]["q3"];

        if ($view->name == 'iamru_prepared_statement') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value',  $q1, '=' );
        }

        if ($view->name == 'iamru_word_for_you_view') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value',  $q3, '=' );
        }

    }

```

# Answer
> 0 votes
You can access the content of a where condition modifying its value:

```
$query->where[0]['field_condition'][0]['value'] = 'something...';

```

Pretty similar what you did with orderby. Also you can add custom where conditions add\_where\_expression

---
Tags: 7, views
---


# Question
Title: How to determine create access for a given enitty and bundle
This one feels like it should be obvious, but after some searching I'm having trouble finding a code example for checking whether a user has create access for an arbitrary entity.

In this case, I'm looking to pass an arbitrary entity type and bundle, in order to check whether a user has create access. This can be any entity type, including custom entities.

I have a sense that the end of the expression will be -\>createAccess() , based on what I've read for the entity access interface classes, but where I'm stuck is finding the right class to call first, in order to get the entity information.

# Answer
OK, I have figured it out. Here's what I am using to get access for the current user (in the createAccess() step the second parameter can be an account, if you need to pass an account):

```
// Before this, you need to get the entity type and bundle,
// shown here as $entity_type and $bundle .
$entity_manager = \Drupal::entityTypeManager();
$access_handler = $entity_manager->getAccessControlHandler($entity_type);
$access = FALSE;
if ($bundle) {
  $access = $access_handler->createAccess($bundle);
}
else {
  $access = $access_handler->createAccess();
}

```
> 3 votes

---
Tags: 8
---


# Question
Title: Ensure that all Cron jobs work correctly
I have a Mobile APP with a Drupal 8 admin backend and I have almost 20 cron jobs running at least 15 times on the day. I'm using Ultimate Cron and Advanced queue modules for handling this. I know that to ensure that all crons running properly, the website should be opened at least once a day or make the crons on the server not on the Drupal site. But, my solution is to create one cron job on the server hitting the website base url to just ensure that all crons will run. So, my question is, does this solution work?

# Answer
> 3 votes
Maybe.

Considering there are 20 cron jobs and they all run 15 times a day and you’re using advanced queue, I would make sure to test in your production environment timeouts and memory issues.

Personally I would use cron + drush making sure the `php.ini` for command line PHP has more than enough resources to accommodate whatever it is you’re doing.

```
drush cron-run

```

https://cgit.drupalcode.org/ultimate\_cron/tree/ultimate\_cron.drush.inc?h=8.x-2.x#n77

# Answer
> 1 votes
If your site is relying so much on Cron you should NEVER trigger it by a user request as this can lead to ruin the user experience.

I don't know what OS you are using but here is a helpful howto for settings up cron jobs in Ubuntu.

---
Tags: 8, cron
---


title: How do I get values of checkboxes?

text:
# Question
Title: How do I get values of checkboxes?
I'm using Drupal 7 and have added checkboxes to a node.

```
$results = query();

foreach ($results as $result) {
  $name = $result['name'];
  $resultarray[$result['id']] = $name;
}

$form['friends'] = array(
  '#title' => "results",
  '#type' => 'checkboxes',
  '#options' => $resultarray,
);

```

On my node the checkboxes show.

Now I'm struggling to get the values of selected checkboxes.

```
function friendmodule_form_submit($form, &$form_state) {

  $friends = $form_state['values']['friends'];

  // do what ever with $friends
}

```

But nothing displays. I've tried echo `$friends`, `print_r`, display them as a Drupal message, but nothing is showing.

What should I do to get the values of selected checkboxes?

# Answer
Assuming that your `$resultarray` variable in the form actually has some data in it, this code will get you a list of the ids that have been selected:

```
function friendmodule_form_submit($form, &$form_state) {
  $friend_ids = array_filter($form_state['values']['friends']);
}

```

When a `checkboxes` element is submitted all of the original option keys will be in the `$form_state['values']'friends']` array, but only the ones that have been selected will have a positive value; the rest will have a value of zero, so you need to use `array_filter()` to extract only the IDs for options that *have* been selected.

Also, at the moment you have a syntax error in your submit function (an extra closing `)`), maybe that's what is causing the error.
> 10 votes

# Answer
### Drupal 8

If I have checkboxes "Friends" and options are like

```
[ ] abc
[ ] def
[ ] ghi
[ ] jkl

```

And I want to know which options user have marked, then use below function.

```
if ($form_state->getValue('friends') != NULL) {

  foreach ($form_state->getValue('friends') as $key => $value) {

    if ($value != 0) {

      $friends = $friends . ", " . $key;
      $friends = substr_replace($friends, "", 0, 1);
    }
  }
}

```

If user has chosen `abc` and `ghi` then you will get `1`, `3` as result in `$friends`. If you wanted to know the value then use

```
$friends = $friends . ", " . $value;

```

It worked for me. I hope it will help you as well.
> 0 votes

---
Tags: 7, nodes, forms
---


# Question
Title: Twig error not in dev (windows) but It is there on hosting (Unix)?
I'm using D8.

I added a field to the user profile:

Lidmaatschapsnummer field\_lidmaatschapsnummer

On my Windows Aquia desktop this is running good. I now ftp'ed all to my hosting and get the error on url:

/admin/people

> Er is onverwacht een fout opgetreden. Probeer het later nog eens.Twig\_Error\_Syntax: A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{" in "{# inline\_template\_start #}\<br\> {{ {{ field\_lidmaatschapsnummer }}" at line 1. in Twig\_ExpressionParser-\>parseHashExpression() (line 302 of vendor/twig/twig/lib/Twig/ExpressionParser.php). Twig\_ExpressionParser-\>parsePrimaryExpression() (Line: 102) Twig\_ExpressionParser-\>getPrimary() (Line: 55) Twig\_ExpressionParser-\>parseExpression() (Line: 149) Twig\_Parser-\>subparse(NULL, ) (Line: 105)

I do not understand how to solve this. The dev is on windows, the hosting on Unix. PHP versions are the same on both.

Any suggestion?

Below is the complete trace:

> Er is onverwacht een fout opgetreden. Probeer het later nog eens.Twig\_Error\_Syntax: A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{" in "{# inline\_template\_start #}\<br\> {{ {{ field\_lidmaatschapsnummer }}" at line 1. in Twig\_ExpressionParser-\>parseHashExpression() (line 302 of vendor/twig/twig/lib/Twig/ExpressionParser.php). Twig\_ExpressionParser-\>parsePrimaryExpression() (Line: 102) Twig\_ExpressionParser-\>getPrimary() (Line: 55) Twig\_ExpressionParser-\>parseExpression() (Line: 149) Twig\_Parser-\>subparse(NULL, ) (Line: 105) Twig\_Parser-\>parse(Object) (Line: 716) Twig\_Environment-\>parse(Object) (Line: 774) Twig\_Environment-\>compileSource(Object) (Line: 452) Twig\_Environment-\>loadTemplate('{# inline\_template\_start #} {{ {{ field\_lidmaatschapsnummer }}', NULL) (Line: 143) Drupal\Core\Template\TwigEnvironment-\>renderInline('{# inline\_template\_start #} {{ {{ field\_lidmaatschapsnummer }}', Array) (Line: 52) Drupal\Core\Render\Element\InlineTemplate::preRenderInlineTemplate(Array) call\_user\_func(Array, Array) (Line: 378) Drupal\Core\Render\Renderer-\>doRender(Array, 1) (Line: 195) Drupal\Core\Render\Renderer-\>render(Array, 1) (Line: 151) Drupal\Core\Render\Renderer-\>Drupal\Core\Render{closure}() (Line: 582) Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 152) Drupal\Core\Render\Renderer-\>renderPlain(Array) (Line: 411) Drupal\views\Plugin\views\PluginBase-\>viewsTokenReplace(' {{ {{ field\_lidmaatschapsnummer }}', Array) (Line: 1347) Drupal\views\Plugin\views\field\FieldPluginBase-\>renderAltered(Array, Array) (Line: 1240) Drupal\views\Plugin\views\field\FieldPluginBase-\>renderText(Array) (Line: 1168) Drupal\views\Plugin\views\field\FieldPluginBase-\>advancedRender(Object) (Line: 226) template\_preprocess\_views\_view\_field(Array, 'views\_view\_field', Array) (Line: 287) Drupal\Core\Theme\ThemeManager-\>render('views\_view\_field', Array) (Line: 437) Drupal\Core\Render\Renderer-\>doRender(Array, ) (Line: 195) Drupal\Core\Render\Renderer-\>render(Array) (Line: 1738) Drupal\views\Plugin\views\field\FieldPluginBase-\>theme(Object) (Line: 761) Drupal\views\Plugin\views\style\StylePluginBase-\>elementPreRenderRow(Array) call\_user\_func(Array, Array) (Line: 378) Drupal\Core\Render\Renderer-\>doRender(Array, ) (Line: 195) Drupal\Core\Render\Renderer-\>render(Array) (Line: 709) Drupal\views\Plugin\views\style\StylePluginBase-\>renderFields(Array) (Line: 576) Drupal\views\Plugin\views\style\StylePluginBase-\>renderGrouping(Array, Array, 1) (Line: 468) Drupal\views\Plugin\views\style\StylePluginBase-\>render(Array) (Line: 2112) Drupal\views\Plugin\views\display\DisplayPluginBase-\>render() (Line: 1533) Drupal\views\ViewExecutable-\>render() (Line: 183) Drupal\views\Plugin\views\display\Page-\>execute() (Line: 1630) Drupal\views\ViewExecutable-\>executeDisplay('page\_1', Array) (Line: 77) Drupal\views\Element\View::preRenderViewElement(Array) call\_user\_func(Array, Array) (Line: 378) Drupal\Core\Render\Renderer-\>doRender(Array, ) (Line: 195) Drupal\Core\Render\Renderer-\>render(Array, ) (Line: 226) Drupal\Core\Render\MainContent\HtmlRenderer-\>Drupal\Core\Render\MainContent{closure}() (Line: 582) Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 227) Drupal\Core\Render\MainContent\HtmlRenderer-\>prepare(Array, Object, Object) (Line: 117) Drupal\Core\Render\MainContent\HtmlRenderer-\>renderResponse(Array, Object, Object) (Line: 90) Drupal\Core\EventSubscriber\MainContentViewSubscriber-\>onViewRenderArray(Object, 'kernel.view', Object) call\_user\_func(Array, Object, 'kernel.view', Object) (Line: 111) Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch('kernel.view', Object) (Line: 156) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 68) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 99) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 78) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 52) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 666) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

# Answer
I think you have an issue(s) in your twig syntax. The error says

> unexpected token "punctuation" of value "{" in "{# inline\_template\_start #}
> {{ {{ field\_lidmaatschapsnummer }}" at line 1.

You may have provided opening parenthesis twice. So, removing one set of opening paranthesis will solve your issue. `{{ field_lidmaatschapsnummer }}`

May this will help you.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Capturing keyup event (JavaScript) from Drupal editors (CKeditor)
I maintain the Textfield Counter module. An issue was raised that the module does not work for textareas with CKEditor enabled. I need to catch a keyup event from editors, or even just the CKEditor module, for the module to work. I haven't worked much with Drupal editors, nor CKEditor. Does anyone have any insight into how to do this, or an alternate solution?

# Answer
Well, once again I've come up with my own answer, though it's not really the one I wanted.

First off, it does not appear that there is any Drupal JavaScript API for interacting with editors. So I had to go directly to the CKEditor API to capture the key up event.

This is the code I was eventually able to use:

```
CKEDITOR.on('instanceReady', function () {
  // Get the HTML ID of the textarea input that would be used if the editor were not enabled:
  var fieldID = $(".some_textarea").attr("id");
  if (CKEDITOR.instances[fieldID]) {
    // Add keyup listener.
    CKEDITOR.instances[fieldID].on("key", function () {
      // The last key pressed isn't available in editor.getData() when
      // the key is pressed. A workaround is to use setTimeout(), with no
      // time set to it, as this moves it to the end of the process queue,
      // when the last pressed key will be available.
      var editor = this;
      window.setTimeout(function () {
        var text = editor.getData();
        // Do something with the text.
        // Also note that the original textarea can be
        // retrieved from editor.element.$. So you could
        // do this:
        var originalTextarea = editor.element.$;
      });
    });
  }
});

```
> 1 votes

---
Tags: 8, javascript, wysiwyg
---


title: db_select sub query

text:
# Question
Title: db_select sub query
I need to use sub query on `db_select` refer the SQL below.

I think the first select should be like `db_select('tabe1','tab')` but this table is a **virtual** table. I have to create temporary only for combining 2 columns with coalesce.

Normal SQL(that works)

```
select nid, field_title_value, field_state_value, newid, e.denomination_ed
from (SELECT nid, n.created, field_title_value, field_state_value, n.uid,
edi.field_edit_target_id, COALESCE(edi.field_edit_target_id, n.uid) AS newid FROM node as n
left join field_data_field_state as et on n.nid = st.entity_id
left join field_data_field_title as ta on n.nid = t.entity_id
left join field_data_field_edit as edi on n.nid = edi.entity_id) as tabe1
left join editor as e on e.uid = tabe1.newid

```

How to do the first `db_select`

# Answer
> 2 votes
This is example for subquery

```
    $subQuery = db_select('users','u');
    $subQuery->fields('u',array('uid'));

    $query = db_select('club_members','cm')->distinct();
    $query->fields('cm',array('country_id','name', 'country'));
    $query->condition('cm.status',1);
    $query->condition('cm.user_id',$subQuery,'NOT IN');
    $resultLow = $query->execute()->fetchAllAssoc('uid');

```

# Answer
> 1 votes
You can try the code:

```
$query = db_select('node', 'n')
  ->fields('n', array('nid'));
$subquery = db_select('node', 'n2')
  ->fields('n2', array('nid'))
  ->join('users', 'u', 'n2.uid = u.uid'
  ->condition('u.status', 0);
$query->condition('', $subquery, 'EXISTS');
$result = $query->execute();

```

---
Tags: database
---


# Question
Title: Rewriting the output of a file download field
I have a content type with two fields, one pdf field which will be downloaded using the Download File module which provides a formatter (file download) to automatically download the pdf file with one click and one image field linked to the pdf field, using the Linked Field module. This works in the node without problems. The problem is when trying to rewrite the results of the image field in Views. I set the file field with the "File download fomatter" and exclude it from display. Then, I try to rewrite results of the image field like this

```
<a href="{{ file_download_field | striptags}}">{{ image_field }}</a>

```

or

```
<a href="{{ file_download_field.url }}">{{ image_field }}</a>

```

but this is not working.

The files are stored in the folder

```
[root]/file-download/download/public[node:field_file_download:entity:fid]

```

What am I missing?

# Answer
The "File download fomatter" you're using doesn't output just the path to the file, it's a more complex formatter and you can't use it in your case as a path to download the file.

In Drupal 8 there is a separate Field in File Views called **URI** that you need to use.

Depending on which Drupal 8 version you're using you'll see only the formatter `File URI` and you need to tick the option **Display the file download URI** to get the link you can use in an anchor href attribute later when overriding fields.

**Do not** enable `Link this field to the file download URL`, this outputs complex anchor HTML, not just the path that you're after.

You can exclude it from display, position it above the image field and `Rewrite results` for the image:

`<a href="{{ uri }}">{{ image_field }}</a>`

or let Drupal link it:
> 1 votes

---
Tags: views, 8
---


# Question
Title: Show English when there is no translation
I have a website for a client, with more than 5 languages (`bg`, `en`, `ru`, `ch`, `de`, `it` ...). The client wants to add a news section but the news should be only in `en` or `ch` and if the user selects a language which is different then `en` or `ch`, `en` should be shown.

Is it possible when you add a content with English language, automatically translations for all other languages to be created instead of adding one by one the translations via translate menu entry?

# Answer
## Language fallback module

I haven't tried this module but it seems to do what you're asking for. You can edit bg, de, it etc languages and set English as the fallback.

Drupal 8 also has one extra module for this: Entity Language Fallback

## Automate with Rules

You could probably come up with a Rule that automatically saves translation nodes of an English node under certain circumstances, with some custom code.

## Quickly fill in translations

If you can't do custom code for what ever reason, you could enable **Synchronize translations** (which is a submodule of i18n) on your Content types. This way when you go to translate other languages you'd already have the English text filled in, images kept etc so you just Save the node and see English text on an Italian node.
> 1 votes

---
Tags: 7, views, i18n-l10n
---


# Question
Title: Can you export and import templates for multi-site use?
Is there a way to take a form built on one site, save it as a template, and use it on another site? Currently all themes and modules are shared so I assumed the Webform Tempaltes would be available on all 3 sites but they are not. Is there a way to do this? This is running on Drupal 8 btw.

# Answer
> 1 votes
If it's Drupal8 you can:

* save webform as a webform template
* export/import the source file.  You can copy it and the paste to the new webform on the other site. It will duplicate an identical webform for you.

---
Tags: webforms
---


# Question
Title: Set custom timer for Slick slideshow based on field value
I have a Slick slideshow. My nodes have a **Timer** field. Right now, I am setting the time of the slick slide like so:

```
Drupal.behaviors.mrpeanut = {
  attach: function (context, settings) {
    var $slider = $("#slick-views-slideshow-page-1-slider");
    $slider.once('mrpeanut').on("afterChange", function(event, slick, currentSlide) {
            slideTime = $('div.slide--' + slick.currentSlide + ' div.field--name-field-timer').text();
            $slider.slick("setOption", "autoplaySpeed", slideTime);
        });
  }
}

```

However, I had some feedback that I may be better off to preprocess the field then attach a JS settings array with all the timer values. This is what I started piecing together based on some discussion in Slack (thanks, @nikathone).

In **mrpeanut.module**:

```
function mrpeanut_preprocess_node(&$variables) {
    $variables['#attached']['library'][] = 'mrpeanut/mrpeanut';
    $node = $variables['node'];
    $slideTime = $node->hasField('field_timer') ? $node->get('field_timer')->value : 20000;
    $slideTime = $slideTime * 1000; // Convert milliseconds to seconds
    $variables['#attached']['drupalSettings']['slideTime'][$node->id()] = $slideTime;
}

```

In **mrpeanut.js**:

```
(function($, Drupal, drupalSettings) {
    Drupal.behaviors.mrpeanut = {
        attach: function(context, settings) {
            var $slider = $("#slick-views-slideshow-page-1-slider");
            var slideTime = drupalSettings.slideTime;

            // Get Node ID from the article
            var nodeAbout = $('.slide').find('article').attr('about');
            var nodeID = nodeAbout.substring(6, $('.slide').find('article').attr('about').length);

            $slider.once('mrpeanut').on("afterChange", function(event, slick, currentSlide) {
                $slider.slick("setOption", "autoplaySpeed", slideTime);
            });
        }
    }
})(jQuery, Drupal, drupalSettings);

```

However, it's not actually setting the correct timer values. One issue I'm having is that I need to capture *all* Node IDs from the view (whereas now I am only getting the first). Second, I'm setting the time slide on the afterChange instead of initially all-at-once.

# Answer
Here's my final **mrpeanut.js**:

```
(function($, Drupal, drupalSettings) {
    Drupal.behaviors.mrpeanut = {
        attach: function(context, settings) {
            var slider = $("#slick-views-slideshow-page-1-slider");
            var slideTime = drupalSettings.slideTime;
            var nodeIdArray = []
            $('article').each(function(i){
                var nodeAbout = $(this).attr('about');
                var nodeID = nodeAbout.substring(6, $(this).attr('about').length);
                nodeIdArray.push(nodeID);
            });

            slider.once('mrpeanut').on("afterChange", function(event, slick, currentSlide) {
                slider.slick('slickSetOption', 'autoplaySpeed', slideTime[nodeIdArray[currentSlide]], true);
            });
        }
    }
})(jQuery, Drupal, drupalSettings);

```
> 0 votes

---
Tags: 8, theming, javascript
---


# Question
Title: Can I change the Display Settings by modifying the database?
I am using Drupal 8.5.6 and need to make the authoring information hidden for each content type. In other words, there should be no 'authored by admin on (date)' on any page. The fix should be simple (How do I hide the authoring information?) but similarly to https://stackoverflow.com/questions/51771776/drupal-8-display-settings-tab-missing-from-all-content-types, I do not have the display settings tab. I can get it back by uninstalling the Manage Display module (I tested on a seperate site), but there is a module dependent on 'Manage Display', which if I uninstall, content that shows up on the main page is lost.

Is there a way to replicate checking the 'Display author and date information' box from the database alone? Or is there a way to change this setting without uninstalling the Manage Display Module?

# Answer
Export the config and change in node.type.\[content-type\].yml:

```
display_submitted: false

```

and import the config again or edit the live config directly with Drush, for example of the content type Article:

```
drush cedit node.type.article

```
> 1 votes

# Answer
Are you trying to NOT display the author information on the page? If so edit the content type. Go to Display settings \> Display author and date information Author username and publish date will be displayed. Mark the box unchecked. From now on any new content will not contain the author information.

You will have to edit all previous content prior to setting this unchecked to not display the author and date information.
> 1 votes

---
Tags: 8, database
---


# Question
Title: Do we need to update every release sequentially to get to the latest version?
Drupal releases a minor release approximately every 6 months, and a patch release every 1 month. Do we need to update to each one of them sequentially in order to get to the latest version? E.g, if I'm on Drupal 8.5.0, and the current Drupal version is 8.6.1, do I need to follow the order and update each release in the order 8.5.0 -\> 8.5.1 -\> 8.5.2 -\> 8.5.3 -\> 8.5.4 -\> 8.5.6 -\> 8.6.0 -\> 8.6.1, or can I directly update to 8.6.1 from 8.5.0 by replacing the core files?

If we can update to 8.6.1 directly, how do we handle the case if a release like 8.5.4 requires changes to 'default.settings.php' but 8.6.1 doesn't require?

# Answer
> 7 votes
You do not need to update Drupal sequentially. The Drupal update system will run all the needed updates so that you can go from (lets say) 8.3.0 to 8.6.1 directly.

Regarding your question about "If we can update to 8.6.1 directly, how do we handle the case if a release like 8.5.4 requires changes to 'default.settings.php' but 8.6.1 doesn't require?" ... If 8.5.4 requires a change to settings.php then 8.6.1 will assume that those changes are there already.

Note: its a good practice to update core (at least for minor versions) so that you are always in a position to quickly apply security releases. The Drupal security team has recently decided to support the most recent 2 minor releases, but still...

Check out this further reading and also this

---
Tags: 8
---


# Question
Title: Get list of nodes by field-collection value
I am having `field_feature` as a collection of fields (`field-collection`) in a content type called 'watches'. Those fields are,

```
field_water_resistance -> water_resistance(Term Reference)
field_gender -> gender(Term Reference)
field_function -> function(Term Reference)
field_sub_function -> sub_function(Term Reference)

```

And so on.

I have my query like this:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'watches','=')
    ->propertyCondition('status', 1);
$query->range($offset, 15);
$query->addTag('joinentity');
$query->addTag('fieldcollection');
$query->addMetaData('termscollection', $filterparams); // $filterparams is array of tids

```

Now I want to add above field collections in the query with the parameters (array of tids). How can we do that?

I know the EntityFieldQuery with the `entity_type` as `field_collection_item` but I don't know the same for `entity_type` as `node`.

How can we do that?

# Answer
> 0 votes
I think you have to possibilities to solve this:

1. Looks like you already got a tag for joining the field\_group entities here:

$query-\>addTag('joinentity');

You could then implement `hook_query_joinentity_alter()` to implement the join, see also EntityFieldQuery INNER JOIN

2. You use db\_select() or db\_query() and add your joins there rather than an EFQ. I think this is preferable as implementing tags and hooks for those gets a bit messy IMO.

---
Tags: 7, entities
---


# Question
Title: "Simple FB Connect" module return page not found when user path replace with another module called "Rename Admin Paths"
Hi I am using "Rename Admin Paths" module for replace "user" path to "account" & working good. But today when I am trying to integrate "Simple FB Connect" module with my drupal 7 site, it return Page Not Found - when try to navigate domain.com/account/simple-fb-connect. But when i try domain.com/user/simple-fb-connect after disable rename\_admin\_paths module, its working, i can connect with facebook.

I am trying to replace all 'user/simple-fb-connect....' path to 'account/simple-fb-connect....' into simple\_fb\_connect modules files, but no luck!

Can anyone help me please... how can i configure simple\_fb\_connect with rename\_admin\_paths module.

Thanks.

# Answer
after 2 days, i solved my problem by change 'user/simple-fb-connect' to 'connection/simple-fb-connect' and its now working.
> 1 votes

---
Tags: 7
---


# Question
Title: How do I add edit/delete buttons to a custom module items list?
I have a custom form on my development site for visitors to create requests, with 3 fields: name, contact, and request.

This is the code in RequestForm.php.

```
public function getFormId() {
  return 'request_form';
}

```

This is the form builder.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['name'] = [
    '#type' => 'textfield',
    '#title' => $this->t('имя'),
  ];
  $form['contact'] = [
    '#type' => 'textfield',
    '#title' => $this->t('контакт'),
  ];
  $form['reqtext'] = [
    '#type' => 'textarea',
    '#title' => $this->t('Текст заявки'),
  ];
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Отправить заявку'),
    '#button_type' => 'primary',
  ];
  return $form;
}

```

The validation handler isn't implemented; I just need to come up with the basics. The user data is stored in the database.

```
public function submitForm(array &$form, FormStateInterface
$form_state) {
  $name = $form_state->getValue('name');
  $contact = $form_state->getValue('contact');
  $reqtext = $form_state->getValue('reqtext');

  $connection = \Drupal::database();
  $result = $connection->insert('request')
    ->fields([
      'name' =>  $name,
      'contact' => $contact,
      'reqtext' =>  $reqtext ,
    ])
    ->execute();
}

```

The requests are saved in the database, and I need to view, edit, and delete them. I created a route to list all of them, using the following code.

### .routing.yml

```
request.list:
path: '/admin/request-list'
defaults:
    _controller: '\Drupal\request\Controller\RequestController::showdata'
    _title: 'Отобразить все заявки'
requirements:
    _role: 'administrator'

```

### The route controller

```
class RequestController extends ControllerBase {
public function showdata() {
  $listall = \Drupal::database()->select('request', 'n');
  $listall->fields('n', array('requestid', 'name', 'contact',
'reqtext'));
  $result=$listall->execute()->fetchAll();

  // Create the row element.
  $rows = array();
  foreach ($result as $row => $content) {
    $rows[] = array(
      'data' => array($content->requestid, $content->name, $content-
>contact, $content->reqtext));
  }

  // Create the header.
  $header = array('requestid', 'name', 'contact', 'reqtext');

  $output = array(
    '#type' => 'table',
    #theme.
    '#header' => $header,
    '#rows' => $rows
  );
  return $output;
}

```

How and where do I implement buttons to edit/delete a certain request?

I'm seeing something like a table:

```
Num Name    Contact        Request                     Options
1   Alex    +7898231231    I need a 10 litres of oil   Edit/Delete
2   John    +7231231231    I need a 50 litres of oil   Edit/Delete

```

I must be missing something, I guess. There is the "right" way to do this in Drupal 8. Any help?

# Answer
You can try code:

```
use Drupal\Core\Link;

[...]

// Create the row element.
$rows = array();
foreach ($result as $row => $content) {
  $rows[] = array('data' => array($content->requestid);
  $rows[] = array('data' => array($content->name);
  $rows[] = array('data' => array($content->contact);
  $rows[] = array('data' => array($content->reqtext);
  //Actions.
  $edit_link = Link::createFromRoute($this->t('Edit'), 'myrouter.edit_form'['id'=>$content->requestid], [
        'absolute' =>
          TRUE
      ]);

$delete_link = Link::createFromRoute($this->t('Delete'),'myrouter.delete_form',['id'=>$content->requestid], ['absolute' => TRUE]);

$build_link_action = [
      'action_edit' => [
      '#type' => 'html_tag',
      '#value' => $edit_link->toString(),
      '#tag' => 'div',
      '#attributes'=>['class'=>['action-edit']]
     ],
     'action_delete' => [
       '#type' => 'html_tag',
       '#value' => $delete_link->toString(),
       '#tag' => 'div',
       '#attributes'=>['class'=>['action-edit']]
       ]
      ];

 $rows[] = ['data' => \Drupal::service('renderer')->render($build_link_action)];
}

// Create the header.
$headers = array('requestid', 'name', 'contact', 'reqtext','options');

$output['results_table'] = [
  '#theme' => 'table',
  '#rows' => $rows,
  '#header' => $headers,
  '#empty' => $this->t('There are no items to display.')
];
return $output

```
> 2 votes

---
Tags: forms, database
---


# Question
Title: Get file field alt text value using entity_metadata_wrapper
I'm trying to get the alt title of a picture using the entity\_metadata\_wrapper.

My code is as follows:

```
$file = file_load($image["fid"]);
$file_wrapper = entity_metadata_wrapper('file', $file);

```

The $image is one of the images i got by using

```
field_get_items("node", $node, "field_images")

```

If i try to get the alt text from the wrapper object, the result is null, although the alt text was set while creating the node.

```
var_dump($file_wrapper->field_file_image_alt_text);

```

outputs an EntityValueWrapper with type "text" and data "null".

```
var_dump($file_wrapper->field_file_image_alt_text->value());

```

returns null.

I don't understand why this is not working, is there any error in my thinking?

# Answer
The file object does not contain the image metadata (Title, Alt,..). You must load the parent node to which the image is attached.

For example to get the Title of the 3rd image in the field "field\_image" you would use:

```
$obj = entity_metadata_wrapper('node', $nid);
$obj->field_image[3]->title = $data;

```

Note 1: you do not have to load the node object first - the $nid variable can be the node id (entity\_id)

Note 2: You should use the dpm() function to inspect the entity instead of var\_dump. If you want to see also values of properties in the inspected entity, you can use a custom function. Google \_wrapper\_debug function to get it.
> 1 votes

# Answer
`var_dump($file_wrapper->field_file_image_alt_text->value());` works for me so I think most likely the alt text is not being saved properly.

Can you confirm that alt text has been set properly when creating the node? I've had issues with the alt text saving the first time before.
> 0 votes

---
Tags: 7, entities
---


title: Execute custom php to manage click2call

text:
# Question
Title: Execute custom php to manage click2call
I need to POST to a url with php code in order to make a phone call. This is an example of javascript:

```
<script>
        function callme() {
            var XHR = new XMLHttpRequest();
            XHR.addEventListener('readystatechange', function() {
                if (XHR.readyState == 4 && XHR.status == 200) {
                    document.getElementById("result").innerHTML = XHR.responseText;
                } else {
                    document.getElementById("result").innerHTML = "ha ocurrido un error: " + XHR.responseText
                }
            });

            var FD  = new FormData();
            FD.append('number', document.getElementById("number").value);
            XHR.open('POST', 'doC2c.php');
            document.getElementById("result").innerHTML = "calling ..."
            XHR.send(FD);
        }
    </script>

```

And the doC2c.php file must be:

```
<?php

$apikey = ""; //API KEY MUST BE PUT HERE GOT FROM DB
$origin = ""; //ORIGIN EXT MUST BE PUT HERE OR GET FROM SOMEWHERE
if ($apikey == "") {
    header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
    echo "APIKEY MISSING";
    die();
} else if ($origin == "") {
    header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
    echo "ORIGIN MISSING";
    die();
} else {
    $opts = array(
       'http' => array(
           'method' => "GET",
           'header' => "Content-type: application/json\n"
                       ."X-Api-Key: ".$apikey,
       )
    );

    $context = stream_context_create($opts);
    $response = file_get_contents("https://....../api/originatecall/".$origin."/".$_POST['number'], false, $context);

    //echo $response;
    echo "CALLING...";
}
?>

```

I would like to make a D8 module that create a URL I could POST to execute the php code, but I want to have Drupal API to query de DB and so on. I know how to make a module with a form and a route to show it, but I don't know how assign a route to a php code file.

# Answer
> A route **is a path** which is defined for Drupal to return some sort of content on

source: Routing system overview

You can think of it like this, a route creates a url that displays a page. This route has a controller which executes the function/method that is in the controller class.

my\_module/**my\_module.routing.yml**

```
my_module.content:
  path: '/fetch'
  defaults:
    _controller: '\Drupal\my_module\Controller\DoC2cController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

```

In the example above when you go to `/fetch` it will execute the content() method that is inside the DoC2cController class php file. This method must return a render array.

For more in depth info read Structure of routes.

my\_module/src/Controller/**DoC2cController.php**

```
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\drupal_set_message;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Defines HelloController class.
 */
class DoC2cController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   *   Return markup array.
   */
  public function content() {

    $apikey = ""; //API KEY MUST BE PUT HERE GOT FROM DB
    $origin = ""; //ORIGIN EXT MUST BE PUT HERE OR GET FROM SOMEWHERE
    if ($apikey == "") {
        drupal_set_message(t('APIKEY MISSING'), 'error');
        throw new NotFoundHttpException();
    } else if ($origin == "") {
        drupal_set_message(t('ORIGIN MISSING'), 'error');
        throw new NotFoundHttpException();
    } else {
        $opts = array(
           'http' => array(
               'method' => "GET",
               'header' => "Content-type: application/json\n"
                           ."X-Api-Key: ".$apikey,
           )
        );

        $context = stream_context_create($opts);
        $response = file_get_contents("https://....../api/originatecall/".$origin."/".$_POST['number'], false, $context);

        //echo $response;
        $response = "CALLING...";
    }

    // Make response string translatable
    $translatable_response = new TranslatableMarkup("@reponse", [
      '@response' => $response,
    ]);

    return [
      '#type' => 'markup',
      '#markup' => $translatable_response,
    ];
  }

}

```
> 3 votes

---
Tags: 8
---