title: Empty value , Contextual Filters

text:
# Question
Title: Empty value , Contextual Filters
This is my problem: I have 3 contextual filters, 2 Content : Has taxonomy term ID and 1 Content :Updated month

if I write in the url : test.com/International/North/06

It will show all the articles update the 06 in the International + North category

But if i write test.com/International/06 or International//06 to show just the articles update the 06 in the International category it doesn't work..

How can hide or set an empty condition on the second contextual filter to access on the third ?

# Answer
contextual filters doesn't necessarily know when something is incorrect - it assumes the values are accurate and attempts to use them as you have it setup. You could do it this way:

* create a custom views handler, or install Views PHP

assuming Views PHP:

* for the second filter, provide a default php value that evaluates the url - if only two arguments are provided assume the second is missing and return all

Of course, this is quite presumptuous on the url information provided to Views, and will inevitably fail in some situations. Depending on how you link to the view and create the url, you are probably better off using a place-holder for the second value `(international/--/06)`, with a similar default value set up as above whereby if the place-holder is found, it would return all
> 0 votes

# Answer
In my case I was wanting to programmatically render the view.

To make the second filter render all I had to use 'all'.

e.g.

views\_embed\_view('notes', 'display\_mode', 'international','all','06')
> 0 votes

---
Tags: views
---


title: What can Menus do that Taxonomy cannot?

text:
# Question
Title: What can Menus do that Taxonomy cannot?
'Comments', 'Users', 'Taxonomy' are Entity Types because they each define their own sets of required fields.

I am having a discussion with my boss where I am arguing that 'Menu' are really just a type of 'Taxonomy'. This is because Taxonomy has a `parent` field, and a `title`, but Menu also ***shares*** this, and extends it to require a 'link' field. He, however, disagrees with me and says that there are things which Menus can do that Taxonomy cannot. But I don't see what.

1. 'Menu' has the concept of hierarchy, so does 'Taxonomy'.
2. 'Menu' has a 'link' field to link to a Node, or an external link. But this can also be done using 'Taxonomy', by manually adding in a 'link' field manually.
3. You can control permissions on 'Menu' items, you can also do this with Taxonomy

I understand that a 'Menu' serves a special and common need, but conceptually I think it's just a type / superset of taxonomy, not another Entity. I think this chain of thought is common, as reflected by the number of sites that uses the Taxonomy Menu module.

In a previous question, I grok that Comments and Nodes are different Entities because they have completely different fields. But here, Menu seems to have the same fields as Taxonomy - namely `parent` and `title`.

So, why has the Drupal community decided that Menu need to be its own Entity Type, instead of a being just a module that extends taxonomy? (i.e. Taxonomy Menu) **What does Menu offer that you cannot achieve in Taxonomy?**

# Answer
> 2 votes
Basic difference I run into some time ago: a menu can link to only one content where taxonomy term can refer to several nodes. So, if you need a relationship node -\> term that allows one node to be marked with many terms (and, in consequence, have one term assigned to many nodes) then menus won't do that for you (at least not out of the box). Node -\> menu relationship is more 1-to-1 where node -\> term is 1-to-many.

# Answer
> 1 votes
Menus:

* provide an "active path" class to help style the menu tree
* have built-in support for multilevel menu functionality
* provide Breadcrumb information (for some breadcrumb implementations)

---
Tags: routes, entities, taxonomy-terms
---


# Question
Title: How can I get an empty region not to render in a field_layout template?
I've got a layout\_discovery template set up like this, for use in a field layout:

```
{% if content %}
<div{{ attributes.addClass(classes) }}>
  <div class="layout-region layout-region--main col-sm-8">
    {{ content.main }}
  </div>

  {% if content.sidebar %}
  <div class="layout-region layout-region--sidebar col-sm-4">
    {{ content.sidebar }}
  </div>
  {% endif %}
</div>
{% endif %}

```

(I have also tried `{% if content.sidebar|trim|length > 0 %}` with no change in the result.)

A content type using this layout puts a single, optional field into the sidebar region. If that field is empty, I would expect content.sidebar to be empty, so that the sidebar div won't be output and the main div can expand to fill the space. However, instead I get an empty sidebar div:

```
<div class="layout-region layout-region--sidebar col-sm-4">
</div>

```

Is there any way to accomplish this in a field layout, or do I need to build a custom node template instead?

# Answer
Use this syntax:

```
{% if content.sidebar %}
  <div class="layout-region layout-region--sidebar col-sm-4">
    {{ content.sidebar }}
 </div>
{% endif %}

```

It will remove all HTML (such as the s that appear even if the section is empty and then only display if there is some non-HTML present.

NOTE: This will not work properly if a region contains only HTML tags, such as Search Facets that are completely made up of options. The striptags call will remove everything from these regions, making them appear to be empty and preventing your facets from showing

See also the discussion here: \[meta\] Themes improperly check renderable arrays when determining visibility.
> 1 votes

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


# Question
Title: Why does $form_state->get('XXX') return an empty value after the form has been submitted?
In the QueueExampleForm.php) file, which is part of the Examples for Developers project, why does `$form_state->get('insert_counter')` always return an empty value after the form has been submitted and an item was inserted into the queue?

# Answer
I think it's a bug. So in order to keep the incrementing textfield. we can remove the setting/getting of the useless arbitrary property "insert\_counter" and exploit the call of existing instruction :

```
$items = $this->retrieveQueue($queue_name);

```

In resume, we can just replace :

```
'#default_value' => $this->t('item @counter', ['@counter' => $form_state->get('insert_counter')]),
by
'#default_value' => $this->t('item @counter', ['@counter' => count($items) + 1]),

```

And remove the `$form_state->setRebuild();` inside the addqueue submit handler
> 0 votes

# Answer
Lets try with

```
$form_State->getValue('insert_counter');

```

or

```
$form_State->get('insert_counter')->getValue();

```
> -1 votes

# Answer
I think try below code

```
$textfield_1 = $form_state->getValue('insert_counter');  //'#tree' => TRUE
 $values = $form_state->getValues(); // '#tree' => TRUE

```
> -1 votes

---
Tags: 8, forms
---


title: How can I install H5P SCORM libraries?

text:
# Question
Title: How can I install H5P SCORM libraries?
The subject says it all. I am attempting to install H5P SCORM libraries in an install of Drupal 7.59 and running into a roadblock: None of what I am reading—or understanding—is clear about how to install the libraries. I am attempting this on macOS High Sierra under MAMP 4.5 (PHP 7.1.12) and MAMP 3.5.2 (PHP 5.6.10). Apache permissions are fine as far as I can see, FWIW and other temp files and uploads work fine on this setup.

I have installed the following two modules in Drupal:

And on the module’s install page I have activated all three modules connected to them:

* **H5P (7.x-1.35)**
* **H5P Editor (7.x-1.35)**
* **H5P SCORM (7.x-2.4)**

But when I go to install the libraries… I just can’t seem to get them to upload without some error happening such as a problem expanding the archive into the `temp/` directory and such. The weird thing is temp direcroures are clearly created, but there is no content in them.

I have even followed the “Better Install Instructions” that appear here as a contributed “issue” but with no luck.

The libraries in question are as follows:

Do the decompressed files need to have a directory name such as `H5PEditor.ScormFile.h5p` or `H5P.Scorm.h5p`? Because if I simply rename the files, the created directory is still `h5p-editor-scorm-master` and `h5p-scorm-master`.

The tangential question is… Is there simply a way I can just physically place files in the correct directory structure user `libraries/`? Or must it be installed via the administration interface? It seems to me if I could just drop those files in, Drupal—and the H5P modules—should be able to see them, right?

# Answer
> 3 votes
See this page about how to manually construct H5P packages and follow the same process for each repo.

You need to download the repo Zip file. Decompress into a temp directory. Delete the `LICENSE`, `README.md`, and `.gitignore` files

Create a new folder to hold the rest of the files like `library.json`, CSS, JS For the H5P editor, name it `H5PEditor.ScormFile`. For the `h5p-scorm-master`, use `H5P.Scorm`:

Outside of the new folder, create an `h5p.json` file.

For the `H5PEditor.ScormFile`, use this:

```
{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    { "machineName": "H5PEditor.ScormFile", "majorVersion": 1, "minorVersion": 0,"patchVersion": 8, }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}

```

for the `H5P.Scorm`, use:

```
{
  "title": "SCORM/xAPI",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    { "machineName": "H5P.Scorm", "majorVersion": 1, "minorVersion": 1, "patchVersion": 16, }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": ["div"]
}

```

Now Zip up the right `h5p.json` folder and the `H5PEditor.Scormfile` or and the other with `H5P.Scorm` directory. Zip compress each, naming the editor file `H5PEditor.ScormFile.h5p` and the second library `H5P.Scorm.h5p`.

### Creating `H5PEditor.ScormFile.h5p`.

So create Zip file renamed to `H5PEditor.ScormFile.h5p`. Inside of that you have a folder named `H5PEditor.ScormFile` with contents of the Git repo, `https://github.com/pavloshevchuk/h5p-editor-scorm`, specified files removed. You also create a `h5p.json` file with the code provided. Place it in the Zip file but outside the `H5PEditor.ScormFile` directory.

```
H5PEditor.ScormFile.h5p
├── H5PEditor.ScormFile
│   ├── library.json
│   ├── scripts
│   │   ├── scormFile.js
│   │   └── scormFileUploader.js
│   └── styles
│       └── scormFile.css
├── H5PEditor.ScormFile.h5p

```

### Creating `H5P.Scorm.h5p`.

Create a second Zip file renamed to `H5P.Scorm.h5p`. Inside of that you have a folder named `H5P.Scorm` with contents of the Git repo: `https://github.com/pavloshevchuk/h5p-scorm`, specified files deleted. Place the `icon.svg` file in a directory called `content`, inside the Zip file. You also create a `h5p.json` file with the code provided. Place it in the Zip file but outside the `H5P.Scorm` directory. The Zip file contains this structure:

```
H5P.Scorm.h5p
├── content
│   └── icon.svg
├── h5p.json
├── H5P.Scorm
│   ├── css
│   │   └── scorm.css
│   ├── js
│   │   ├── api
│   │   │   ├── api_1_2.js
│   │   │   ├── api_2004.js
│   │   │   ├── datamodel.js
│   │   │   ├── debug.js
│   │   │   └── flash_detect.js
│   │   └── scorm.js
│   ├── library.json
│   └── semantics.json

```

You should now have two H5P files and you will now be able to update them at the H5P admin libraries page:

```
admin/content/h5p

```

Here's a repo containing the files I made following these instructions: https://github.com/jackrabbithanna/h5p-scorm-libraries

---
Tags: 7, theming
---


# Question
Title: URL alias to access user profile as admin
I realized that users on my site have their path ending in the form "user/number" (for example: user/3) when I check People in the Admin Toolbar and click on their username. I would like to use URL aliasing or some alternative that allows the path end with their username (for example: user/john\_smith). How can I do this?

# Answer
You can create aliases using the Pathauto module.

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

There are various tutorials of this module you can watch.
> 2 votes

---
Tags: users, path-aliases
---


# Question
Title: Drupal core language module, language switcher block
Can a preprocess hook convert the default ul of hyperlinks into a drop-down select list? Something like this hook.

```
function THEME_preprocess_links__language_block(&$variables)

```

# Answer
You can copy the `core/modules/system/templates/links.html.twig` into your theme's templates directory, call it `links--language-block.html.twig` and in this file adjust the output from the default ul/li structure into a different html structure.

**NOTE:** there is already 3 maybe more modules that convert the language switcher to dropdown lang\_dropdown, dropdown\_language and bootstrap\_languages.
> 2 votes

---
Tags: 8, javascript
---


# Question
Title: Display a block based on current select option
I have a select field that holds two options. When the second option is chosen, I want to display a block.

I know that with form API I should be able to do this. I'm just not sure on where to start. Any help getting me going would be greatly appreciated.

So far I have the code below.

```
function MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['account']['type'] = [
      '#title' => 'I am ordering for',
      '#type' => 'select',
      '#options' => [ 'Myself' => 'Myself', 'Someone' => 'Someone else' ],
      '#weight' => -100
      ];
}

```

# Answer
Don't try to add the fields in a form alter hook. Do this in the field UI of the user entity `/admin/config/people/accounts/fields`. To change the visibility of fields dependending on the content of another field use

Conditional Fields

or the Form #states API directly, see How can I hide or show fields using states with hook form alter.

**EDIT:** The form #states api did the trick.
> 1 votes

---
Tags: 8, javascript, blocks
---


# Question
Title: How to store data in database with Form API?
I'm new to developing Drupal 7 modules, and I can't figure out why my custom module's form data is not stored in my database's table called '`media_skins`'.

I followed the info explained in Creating modules - a tutorial: Drupal 7.x but I can't get it working. What's wrong with my code?

Here's my code:

```
function media_skins_menu() {
  $items = array();
  $items['admin/config/content/media_skins'] = array(
    'title' => 'Media Skins',
    'description' => 'Configuration for Skins module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('media_skins_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function media_skins_form($form, &$form_state) {

  $form['media_skins_test'] = array(
    '#type' => 'textfield',
    '#title' => t('Test field'),
    '#size' => 20,
    '#maxlength' => 20,
    '#description' => t('Test info for the field.'),
    '#required' => FALSE,
  );
  return system_settings_form($form);
}

function media_skins_form_validate($form, &$form_state) {
    // For now, I will no validate anything
}

function media_skins_form_submit($form, &$form_state) {
  $form = db_insert('media_skins')->fields(
    array(
      'start_date' => $form_state['values']['media_skins_test'],
    )
  )
  ->execute();
  drupal_set_message('Data stored in database successfully');
}

```

Any help will be very appreciated.

**EDITING THE SCENARIO**

After reading your comments, I tried the following, but I get "Unexpected error, try it again":

```
function media_skins_form($form, &$form_state) {
  $form['media_skins_test'] = array(
    '#type' => 'textfield',
    '#title' => t('Test field'),
    '#size' => 20,
    '#maxlength' => 20,
    '#description' => t('Test info for the field.'),
    '#required' => FALSE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Enviar'),
  );
  return $form;
}

```

# Answer
To use your own form submit handler, you should not use **system\_settings\_form** in your form, instead just return your form.

If you are just going to save your value in your submit handler, go with **system\_settings\_form**. To get the values, use `variable_get('your form field name')`. In your case, you can use `variable_get('media_skins_test');`
> 0 votes

# Answer
You have to variable\_get like below.Now you can get the values why because it will store in the variable table.

```
function media_skins_menu() {
  $items = array();
  $items['admin/config/content/media_skins'] = array(
    'title' => 'Media Skins',
    'description' => 'Configuration for Skins module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('media_skins_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function media_skins_form($form, &$form_state) {

  $form['media_skins_test'] = array(
    '#type' => 'textfield',
    '#title' => t('Test field'),
    '#size' => 20,
    '#maxlength' => 20,
    '#description' => t('Test info for the field.'),
    '#required' => FALSE,
    '#default_value' => variable_get('media_skins_test', 10),
  );
  return system_settings_form($form);
}

function media_skins_form_submit($form, $form_state) {
    variable_set('media_skins_test', $edit['demo_number']);

}

```

in devel/php you can see the results of the textfield

$test = variable\_get('media\_skins\_test'); dpm($test);
> 0 votes

---
Tags: 7, forms, database
---


title: Facets display values instead of labels

text:
# Question
Title: Facets display values instead of labels
I am using the facets module to add filter blocks in my view.

I have a list field wich contains

> FR|France
>
> IT|Italy

My dropdown list of facet display values (fr, it)

I want to display (France, Italy)

How can I do that?

Thank you

# Answer
try in search API \> your index \> search your field and then in the column type, select STRING.

Also maybe you can hook your field:

```
function HOOK_facet_items_alter(&$build, &$settings) {
   if ($settings->facet == "YOUR_FACET_NAME") {
       foreach($build as $key => $item) {
          $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
        }
    }
}

```
> 0 votes

---
Tags: 7, search
---


title: Full content view mode per role

text:
# Question
Title: Full content view mode per role
I've looked around but didn't find the right solution. In D7.5x I would like to create different view modes (of Full Content) per role. I am using Display Suite.

The situation should be like this: I have teaser view mode, Full content (limited) view mode, Full Content (extra) view mode. Is there any quick solution, to let users with role A after clicking onto link in teaser view mode get to see Full content (limited) and users with role B get Full content (extra)?

tnx

# Answer
Oh, It looks like I've found an answer myself, so I will post it here in case someone will have similar issue. One of the solutions (I am still not sure if this is the optimal one, but it works) is to use module Contextual View Modes (It requires Context module and Entity API). With this combination of modules it is possible to create context rules where in Conditions section there is particular user role and in Reactions one must define particular View mode for Content Type. And that's it! It just requires at least 3 modules to be installed, so maybe there is some simplier solution...
> 0 votes

---
Tags: users, display-suite
---


# Question
Title: How to import content to Drupal 8 site by inserting it directly in the database?
As I was not able to find any working way of importing content from csv, I decided to export it to .csv from the old site (database) and import it then into the Drupal 8 database. However, after I updated tables `node`, `node__body` and `node_field_data` I was not able to access the content overview page anymore.

# Answer
Turned out that I also had to update `node_revision` table, so all I have done was:

**`node` (D7) -\> `node` (D8)**

`select nid,vid, 'article', UUID(), language
from node
where type = 'story'`

**`field_data_body` (D7) -\> `node_body` (D8)**

`select 'article', null, entity_id, revision_id, language, 0, body_value, body_summary, 'basic_html'
from field_data_body
where bundle = 'story'`

**`node` (D7) -\> `node_field_data` (D8)**

`select nid, vid, 'article', language, status, title, uid, created, changed, promote, sticky, 1, 1
from node
where type='story'`

**`node` (D7) -\> `node_revision` (D8)**

`select nid, vid, language, created, uid, null, 1
from node
where type='story'`

**`node` (D7) -\> `node_field_revision` (D8)**

`select nid, vid, language, status, title, uid, created, changed, promote, sticky, null, language
from node
where type='story'`

Of course, these are just simple queries for just one particular article type without any additional fields, but the point was to show which tables need to be updated to at least get the content in the Drupal 8. Other (field) tables will require more sophisticated SQL exports.
> 1 votes

---
Tags: 8, database, importing-exporting
---


title: Display node as a popup window

text:
# Question
Title: Display node as a popup window
I am new to Drupal. I have a form which adds details of user to my table. I want to display that node in a popup window. How would I do this?

# Answer
There are a lot of solutions for this kind of stuff. I would do it in the theme layer to have something really light. You can also use the variety of popup modules for this. One simple way to do this, use the Lightbox2 module, checkout this documentation page: http://drupal.org/node/252260
> 3 votes

# Answer
Use the Colorbox Node module:

> Gives the user the ability to display ANY page inside a colorbox modal without the header and footer. Those pages include:

This is an apt module for pop up a node.
> 2 votes

# Answer
The best way is actually this module:

http://drupal.org/sandbox/yuriseki/1771028

The only think you need to do is adapting the path and you're done!
> 0 votes

# Answer
Using colorbox node module to open node content inside the Colorbox.

Download Colorbox and Colorbox\_node Module from drupal.org site You also need to download colorbox library and copy to `sites/all/libraries/colorbox`

Install both module and enable it from modules list. after You should create link either manually or using views or whatever the way you want. e.g.

```
<a class="colorbox-node" href="node/123?width=600&height=600">Page1</a>
<a class="colorbox-node" href="node/123" data-href="node/123?width=600&height=600">Page2</a>
<a class="colorbox-node" href="node/123" data-inner-width="600" data-inner-height="600">Page3</a>

```

You should specify `width` and `height` of colorbox to fit your content.

**Gallery Support**

```
<a class="colorbox-node" href="blogs/my-example?width=600&height=600" rel="gallery">My Example</a>

```

> Also integrate with Views/Context/Panels Support
> 0 votes

# Answer
## Node pop-up

> Node pop-up module create paths for popup node view without any dependency (only Drupal 7 core functionally used for creation popup window).

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

> ### HOW TO
>
> 1. Enable module
> 2. Create link.
>     1. Variant 1: Set data-npop="NODE\_NID" (recomended)
>     2. Variant 2: Set href attribute as "ajax/npop/node/\[nid\]/load/nojs", where \[nid\] nid of node and set link class "use-ajax".
> 0 votes

---
Tags: 7
---


# Question
Title: Passing field value to #autocomplete_route_name in custom form
I am creating a custom form where I have 2 fields.

1. Taxonomy : select field having list of vocabularies.
2. Terms : Autocomplete field having terms list.

When I start typing in terms field, the value of the term field is passed to the routing function. However I also need the value of the taxonomy field in routing function so that I can restrict the terms list.

Is there anyway that I can get the other field values in the routing function?

Here is my buildform function :

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['taxonomy'] = [
    '#type' => 'select',
    '#title' => $this->t('Select Taxonomy'),
    '#options' => $taxonomies,
  ];

  $form['taxonomy_terms'] = [
    '#type' => 'textfield',
    '#autocomplete_route_name' => 'unido_drupal_admin.get_taxonomies'
  ];

  return $form;
}

```

Here is my routing function :

```
public function get_taxonomies(Request $request) {
  // Here I need to get taxonomy field value to restrict the result.
  $params = $request->query->all();
  $result = \Drupal\taxonomy\Entity\Vocabulary::loadMultiple();
}

```

Thanks.

# Answer
You need to define `#autocomplete_route_parameters`. I'm not sure if the form gets rebuilt during autocomplete queries (most likely not!) so you might need to define a `#ajax` on the vocabulary selector in order to rebuild the form and return the `taxonomy_terms` field with correct parameters set. This way you're defining a clear dependency, that field 2's available values depend on field 1's value. Below code is untested, but hopefully pushed you in the right direction:

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['taxonomy'] = [
    '#type' => 'select',
    '#title' => $this->t('Select Taxonomy'),
    '#options' => $taxonomies,
    '#ajax' => [
      'callback' => 'Namespace\To\Your\Entity::vocabulary_callback',
      'event' => 'change',
      'wrapper' => 'term-wrapper'
    ],
  ];

  // Initially return a disabled field.
  $form['taxonomy_terms'] = [
    '#type' => 'textfield',
    '#disabled' => TRUE,
    '#prefix' => '<div id="term-wrapper">',
    '#suffix' => '</div>',
  ];

  // If someone's chosen a vocabulary, rewrite the field.
  if ($vid = $form_state->getValue('taxonomy', false)) {
    $form['taxonomy_terms'] = [
      '#type' => 'textfield',
      '#prefix' => '<div id="term-wrapper">',
      '#suffix' => '</div>',
      '#autocomplete_route_name' => 'unido_drupal_admin.get_taxonomies',
      '#autocomplete_route_parameters' => ['vid' => $vid],
    ];
  }

  return $form;
}

public function vocabulary_callback(array &$form, FormStateInterface $form_state) {
  return $form['taxonomy_terms'];
}

```

You also need to define this as a route parameter in your route's `path` element:

```
unido_drupal_admin.get_taxonomies:
  path: '/path/to/your/autocomplete/{vid}'

```

And also accept the parameter in your autocomplete function:

```
public function get_taxonomies(Request $request, $vid) {

```

There might be better ways to do this though, but with my limited D8 knowledge, this is how I'd approach it.
> 2 votes

---
Tags: 8, forms
---


# Question
Title: How to Show Multiple field value according to Row Height
In Content type Having field Work Images and enter the content for that and set the relationship and CONTEXTUAL FILTERS for the frontend. Content Is showing fine But its showing random. How can I show the value as in same order as in backend ? Any Suggestion ?

# Answer
You need to sort by the field delta (The position in the list). So in views add "sort criteria" and search for "work images delta"
> 2 votes

---
Tags: views, nodes, commerce
---


# Question
Title: LDAP Feeds example not importing new users - Undefined index: count in FeedsLdapEntryParser
I followed the LDAP Feeds example from the documentation and the query test returns the user fields just fine, but after launching the cron job manually I get **"There are no new users."** \+ notice:

> "Notice: **Undefined index: count in** FeedsLdapEntryParser-\>parse() (line 20 of /var/www/html/drupal/sites/all/modules/ldap/ldap\_feeds/FeedsLdapEntryParser.inc). LDAP Users Imported Successfully."

I triple checked my configurations, as well as the mapping which got **unique targets** for both User name (name) and mail. I also posted in the drupal module issue as I would think importing users via LDAP is a very much needed function.

Has anybody been successful importing that way or any idea why the count is making issues?

FYI my LDAP Query Results: count=1574. Could it be limited to certain amount of user entries?

# Answer
> 0 votes
Not sure what exactly resolved this but basically I **added GUID as a unique field** with a unique number and while manually running the cron job **/admin/config/system/cron** didn't add the users,

after I went to **/import/ldap\_data\_to\_user\_data** and scheduled the LDAP query for import it worked.

Now it also syncs after I run them manually. Not sure what i did wrong or was missing, slightly confused but happy :)

---
Tags: feeds, authentication-authorization
---


# Question
Title: Specifying Taxonomy Term Filter in View from Page Editor
I'm currently using a view to display content teasers and I want my users who are making pages to be able to incorporate these views, however I want them to be able to specify a taxonomy term to show that content. I tried doing this with a Contextual Filter, however I need some way to allow the user to specify the term in the page editor, not on the page preview itself. Is this something that Views allows you to do? Do I need to install a module, or do this programatically?

Hopefully I'm not being too confusing with that description, if so just let me know and I can try and clarify.

# Answer
> 0 votes
There are two parts to this question - one is to have creators of nodes to choose a Taxonomy term, the other is to have a Views Display show up on Node View based on the Taxonomy term set inside the node.

## Taxonomy term reference

As you've already worked out, the easiest way to allow for users to influence what content list to display on their nodes is to allow them to choose a Taxonomy term.

You can do that by creating an Entity reference field referencing Taxonomy terms. The way you worded your question suggests you will only allow one term to be selected (limit number of values to 1).

When the node is saved, the information about the chosen Taxonomy term will be displayed when viewing the node. If you don't want this to be visible, if you only want this field to serve as a way to influence Views in the following steps, you can hide the field from showing up on node view by changing `Manage Display` settings. The info from the field will still be available for Views to read "on the sly".

## Views Block listing content sensitive to the Taxonomy of the page they're on

Creating Views that display related content is probably the most common request in Views. With such a Views Block you don't have to have any additional interface for node creators to choose what to display on their nodes. Simply having a Taxonomy term reference is enough (already covered above).

First you create a Views Block listing your desired Content (set up all the regular Filters and Fields).

Then add a Contextual Filter of type `Content: Has taxonomy term ID`, and configure it to Load filter from node page (NOT taxonomy term page). Take a look at screenshots from this answer: display lists of related content that share the same Taxonomy term.

In the end place the Block in a region, and configure the block settings (to display only on node page where you want).

When your content creators save a new node, that Block will automagically show only Teasers of content tagged with the term they chose when creating the node.

If the content type of the created node is the same as the content type of teasers in the Block, the newly created node will also be displayed on the Teaser list. If you don't want the node you're currently viewing to be listed there you can exclude it with an additional Contextual Filter `Content: ID` (Provide default value: Content Id from URL, More (at the bottom): Exclude).

---
Tags: views
---


# Question
Title: Create view with path relative to taxonomy term
I have multiple content types and would like to create a couple of views to show various content types as sub directory to the term page.

The challenge is that I need to the path to be taxonomy/term/%/content-type1 taxonomy/term/%/content-type2

Tired using tokens in the views path. It didn't work.

Any other suggestions?

# Answer
> 6 votes
The way to influence filtering Views through URL arguments is to use Contextual filters. For each URL sensitive Contextual filter you get one argument in your URL (separated by `/`).

In your case you need to add a new Contextual Filter of type `Content: Content type` and configure it:
When the filter value is NOT in the URL
**Provide default value**
**Raw value from URL**
**Path component**: **4**
When the filter value IS in the URL or a default is provided
**Specify validation criteria**
**Content type**
**Single ID**
**Case in path**: **Lowercase**
More
**Transform spaces to dashes in URL**

Change the `Path` of your Page from `taxonomy/term/%` to `taxonomy/term/%/%`.

Now when you visit `taxonomy/term/1/article` it will list all articles tagged with the term 1 (I'm assuming you have cloned the default Taxonomy term Views).

---

## Show term names instead of TID in URL

It is possible to pass term names to Views from URL, instead of using term ID numbers. So the URL might look something like: `taxonomy/term/tag1/article`

To achieve that we have to introduce the term name into Views. In this example we cloned the default Taxonomy term Views, and they only have term ID available.

To introduce more information about the taxonomy term we add a new Relationship. In this case we add **Taxonomy term referenced from field\_myvocabulary** (use your Entity reference field referencing the term from the relavant vocabulary).

There are no consequences of this step visible from the outside, but from the inside we have more choices to choose from when adding new Contextual Filters. One of those new choices is **Name** from **Taxonomy term** Category. Add that as a new Contextual Filter and configure it:
Relationship: field\_myvocabulary: Taxonomy term
**Provide default value**
**Raw value from URL**
**Path component**: **2**
When the filter value IS in the URL or a default is provided
**Specify validation criteria**
**Taxonomy term name**
Vocabulary: **My Vocabulary**
**Transform dashes in URL to spaces in term name filter values**
More
**Transform spaces to dashes in URL**

Rearrange the Contextual filters to have that Name filter first, then the Content type second and you can ignore or remove the original "Has taxonomy term ID" in third place.

Now you can enter `tag1/article` into the Preview and you'll see the results, all with using human-friendly URL bits. `or visit /hub/tag1/article` on your site.

Relationships can introduce duplicate results. If this happens make sure your filters have turned on "Reduce duplicates" option, although you'll probably have to edit your Views **Query settings** and set them **Distinct**.

Be careful about the Case settings and converting spaces to dashes and vice versa. Your term name might be "Best term", and depending on your Contextual filters settings you might need to enter "best term" or "Best-term" etc.

The default Taxonomy term Views renders Taxonomy term in Views Header area. I haven't been able to make it work with the Taxonomy name though. It does work if you keep the ID as the third filter and use path `tag1/article/1`.

But you can solve it (if you need this feature of rendered Taxonomy term in Views Header) with the help of an additional module: Views taxonomy term name into ID and the patch mentioned there.

You can also use this module to get term name in URL, instead of using a Relationship like explained above ;)

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


# Question
Title: Cycle comments on field--comment.html.twig
I would like to add a div for every comment on my field--comment.html.twig

On the template I've a "comments" variable, but if I cycle in this way, I obtain error (Fatal error: "0" is an invalid render array key in /var/www/html/core/lib/Drupal/Core/Render/Element.php on line 97):

```
{% for comment in comments %}
      {{ comment }}
  {% endfor %}

```

I would like to add "odd/even" class to comments.

\[EDIT\] If I use a cycle like this:

```
{% for key,value in comments %}
  {{ dump(key) }}
{% endfor %}

```

keys are: #sorted, #pre\_render, 'pager', '106', '107' (where 106 and 107 are comment ids)

# Answer
You can try something like this:

```
   {% set pre_render = comments['#pre_render'] %}

   {% for key, item in comments if key|first != '#' %}
     {% if key != 'pager' %}
       {% set item = { '#pre_render': pre_render, 0: item } %}
       <div class="comment-{{ cycle(['odd', 'even'], loop.index0) }}">{{ item }}</div>
     {% else %}
       <div class="comment-pager">{{ item }}</div>
     {% endif %}
   {% endfor %}

```
> 5 votes

# Answer
Loop and set the odd-even classes by using following code:

```
  {% for comment in comments %}
            {% set classes = cycle(['odd', 'even'], loop.index0) %}
            <div{{ comment.attributes.addClass('comment-', classes ) }} >{{ comment}}</div>
    {% endfor %}

```
> 1 votes

---
Tags: theming, comments
---


# Question
Title: How to send an email to select set of users for moderation states?
We are using the following modules below for content moderation. Currently have we have 5 people with the Content Approver role and all of them are sent an email when a state transition occurs. There is a need to send email alerts of moderation transitions for certain content types that need approval to just 2 out of the 5 Approvers.

How to send an email to select set of users when changing moderation state?

Expected Results:

When a content editor marks a page ready for Review, they are allowed to manually select one or more users to send an email alert to regardless of Role.

Enabled Modules:

1. Workbench v8.x-1.0
2. Workbench Email v8.x-1.0-alpha7

# Answer
As per @Matoeil's answer you could probably do this with rules.

You could add an entity reference field, limited to 5 values (or more if you want), and you could use a view to limit the available options (users) based on role. Then you could use rules send an email to the referenced users.
> 0 votes

# Answer
you can maybe use rules module

alternatively create a custom module and you can inspire from this, that is used with core content moderation module:

```
use  \Drupal\user\Entity\User;

/**
 *
 *
 * Envoie de mail en fonction des transitions le modération de contenu.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 */
function my_module_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() !== 'content_moderation_state') {
    return;
  }

  $article_id = $entity->get('content_entity_id')->getString();
  $article = \Drupal\node\Entity\Node::load($article_id);
  if ($article->bundle() !== 'article') {
    return;
  }

  global $base_url;

  $article_title = $article->get('title')->getString();
  $article_url = $base_url . "/node/" . $article->get('nid')->getString();

  $author_name = $article->getOwner()->get('field_cn_ldap')->getString();
  $author_email = $article->getOwner()->getEmail();
  $current_user_uid = \Drupal::currentUser()->id();
  $current_user_name = \Drupal\user\Entity\User::load($current_user_uid)
    ->get('field_cn_ldap')
    ->getString();
  $is_author = ($current_user_name == $author_name);

  $uids = \Drupal::entityQuery('user')
    ->condition('status', 1)
    ->condition('roles', 'redacteur_en_chef')
    ->execute();
  ;
  $users = User::loadMultiple($uids);

  $emails_redacteur_en_chef = [];
  foreach ($users as $user) {
    $emails_redacteur_en_chef[] = $user->getEmail();
  }
  $emails_redacteur_en_chef = implode(',', $emails_redacteur_en_chef);

  $moderation_state = $entity->get('moderation_state')->getString();
  $moderation_state_original = '';
  if ($entity->original) {
    $moderation_state_original = $entity->original->get('moderation_state')
      ->getString();
  }
  $is_transition_change = ($moderation_state !== $moderation_state_original);

  include 'includes/notification/messages.php';
  include 'includes/notification/titles.php';
  $send_to = $author_email;
  $params['node_title'] = $title_mod;
  $params['message'] = $message_same_state;
  $send = FALSE;

  switch ($moderation_state) {
    case 'draft':
      if (!$is_transition_change && !$is_author) {
        $send = TRUE;
      }
      break;

    case 'relecture':
      if (!$is_transition_change && !$is_author) {
        $send = TRUE;
      }
      elseif ($is_transition_change) {
        $send_to = "joe@google.fr";
        $params['node_title'] = $title_prop;
        $params['message'] = $message_prop;
        $send = TRUE;
      }
      break;

    case 'relecture1':
      if (!$is_transition_change && !$is_author) {
        $send = TRUE;
      }
      elseif ($is_transition_change) {
        $send_to = "whatever@yahoo.com";
        $params['node_title'] = $title_relec1;
        $params['message'] = $message_relec1;
        $send = TRUE;
      }
      break;

    case 'relecture2':
      $send_to = $emails_redacteur_en_chef;
      $params['node_title'] = $title_relec2;
      $params['message'] = $message_relec2;
      $send = TRUE;
      break;

    case 'published':
      if (!$is_transition_change) {
        $send_to .= ',';
        $send_to .= $emails_redacteur_en_chef;
        $send = TRUE;
      }
      else {

        $send_to = "all@hotmail.com";
        $params['node_title'] = $title_pub;
        $params['message'] = $message_pub;
        $send = TRUE;
      }
      break;

    case 'maj':
      $send_to = "whatever@wahtever.com";
      $params['node_title'] = $title_maj;
      $params['message'] = $message_maj;
      $send = TRUE;
      break;

    default:
      break;
  }

  if ($send) {
    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = "amu_dud_rules";
    $key = 'state_changed_action';
    $to = $send_to;

    $langcode = \Drupal::currentUser()->getPreferredLangcode();

    $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

    if ($result['result'] !== TRUE) {
      drupal_set_message(t('There was a problem sending notifications.'), 'error');
    }
    else {
      drupal_set_message(t("A notification has been sent to $to"));
    }
  }
}

/**
 * Implements hook_mail().
 */
function my_module_mail($key, &$message, $params) {
  $options = [
    'langcode' => $message['langcode'],
  ];
  switch ($key) {
    case 'state_changed_action':
      //$message['from'] = \Drupal::config('system.site')->get('mail');
      $from = 'from@from.com';

      $message['from'] = $from;
      $message['headers']['From'] = $from;
      $message['headers']['Sender'] = $from;
      $message['headers']['Return-Path'] = $from;
      $message['subject'] = t('@title', ['@title' => $params['node_title']], $options);
      $message['body'][] = $params['message'];
      break;
  }
}

```
> 1 votes

---
Tags: 8, users, emails, workbench
---


# Question
Title: Changing hash throw: Uncaught Error: Syntax error, unrecognized expression
I want to change the hash in the URL when I trigger an action (a click for instance) using a pattern like `#/param-1=foo&param-2=bar`

In a fresh Drupal 8 theme, when I try this, I got an error saying *Uncaught Error: Syntax error, unrecognized expression: #/test=0*

It works fine when I try with `#param1-foo_param2-bar` but I would like more flexibility. It looks like jquery is trying to consider the hash as a selector and returns an error that says it's not a valid selector.

Here is the code I use on a fresh classy based theme:

```
(function ($, Drupal) {
    Drupal.behaviors.myModuleBehavior = {
        attach: function (context, settings) {
            $('.layout-container', context).once('myModuleBehavior').each(function () {
                $('.site-name a').on('click', function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    console.log("clicking on logo");
                    window.location.hash = "/test=0";
                });
            });
        }
    };
})(jQuery, Drupal);

```

And here is the result I get from chrome console:

# Answer
`handleFragmentLinkClickOrHashChange` is a function defined in the Drupal script `form.js` which attempts to scroll to the corresponding element when the hash (anchor tag) changes, mimicking browser behavior when the anchor tag is changed through visiting a link.

I know it's common to (ab)use the anchor tag like this in Angular and other frameworks but looks like you are going to struggle if you try to combine it with a regular Drupal frontend.
> 0 votes

# Answer
Thanks to @Alfred Armstrong pointing down `form.js`. It seems this event is responsible of that behaviour:

```
 $(window).on('hashchange.form-fragment', debouncedHandleFragmentLinkClickOrHashChange);

```

It looks like unbinding it in my custom .js does the trick. We won't benefit from the scroll functionality `form.js` provides, but we could recreate it with:

```
$(window).off('hashchange.form-fragment').on('hashchange', function() {
    //something that scroll
});

```
> 3 votes

---
Tags: 8, javascript
---


# Question
Title: How to configure Wysiwyg + Ckeditor Library not to breaks source code lines
I'm using WYSIWYG Module with ckeditor as an editor.
I use it with the full\_html format

My problem is that when switching from the rich-code to the source code view all the line breaks are removed.

So this portion of code :

```
<div class="highlight">
    <p>Nemo enim <a href="#">ipsam voluptatem quaerat voluptatem.</a></p>
</div>
<div class="body">
    <p><strong>Doloremque laudantium,</strong> totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
</div>

```

transforms into something like this :

```
<div class="highlight"><p>Nemo enim <a href="#">ipsam voluptatem quaerat voluptatem.</a></p></div><div class="body"><p><strong>Doloremque laudantium,</strong> totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p></div>

```

Is there a configuration that prevents this from happening ?

# Answer
I think what you are looking for is WYSIWYG Linebreaks.
> 1 votes

---
Tags: 7, wysiwyg
---


title: Html mail gets broken by new lines

text:
# Question
Title: Html mail gets broken by new lines
I am using the *Mail system* and the Swift mailer\* modules to send HTML emails. I then implemented a custom module to send HTML newsletters to users, and I noticed the emails didn't look as expected: Many styles kept broking randomly.

After digging, I discovered the problem was with the string of email randomly being broken by new lines: If a new line came in a critical position in the string, the whole mail would be broken. I needed to know where these strange new lines were coming from.

It turned out I am not doing anything to string expect this.

```
$body = 'some html code without new lines';
$body .= 'some more html code without new lines';
$body .= 'some more and some more html code without new lines';

$params['body'] = Markup::create($body);
$language = $recipient['lang'];
$to = $recipient['mail'];
$params['to'] = $to;
$result = $mailManager->mail('custom_newsletter_mail', 'newsletter', $to, $language, $params, $from, $send_bool);

```

I don't know what `Markup::create($body)` does, so I tried removing it. The email was delivered with no new lines, but the HTML was not rendered.

In mail system configuration, I set swiftmailer as FORMATTER and default PHP mailer as SENDER.

This is the custom module's .module file.

```
function custom_newsletter_mail_mail($key, &$message, $params) {
  $message['body'] = [];
  $message['subject'] = [];
  $message['format'] = 'text/html';
  $message['subject'] = $params['title'];
  $message['body'][] = $params['body'];
  $message['headers'] = array(
    'content-type' => 'text/html',
    'charset' => 'UTF-8',
    'format' => 'flowed',
    'delsp' => 'yes',
    'from' => $params['from']
  );
}

```

I found out that my testing environment send emails with no new lines (Email looks as expected), while my production environment doesn't. I double checked every setting; both are identical as far as I can tell.

I tried using mime mail instead of swift mailer and it WORKED!! there is no newlines or spaces (The HTML mail actually looks good), BUT mime mail only reaches live mails. It doesn't work with yahoo or gmail for some reason.

I need to fix this. I need to remove those annoying new lines in the email body, which I feel it's a swift mailer issue.

# Answer
> 2 votes
**You cannot send email without line breaks**.

The SMTP standard **requires** that lines be limited to 1000 characters. 998 really because the line must end with `"\r\n"`.

If you successfully avoid having line breaks inserted for you, what will happen is that many email servers on the Internet will reject your email. Some will accept it, because they decided to ignore the standards. Guess who does that.

Many servers will not.

The correct answer to this problem is to create HTML email that has line breaks. This is really easy to do. Pick a few elements that occur fairly often, like `</tr>` if you use tables, and CSS rule end braces, and put a newline after it.

Reviewing your HTML will also help you avoid very stupid looking HTML text, if you care. I was just viewing source on a newsletter email from TweakTown where they first include a bunch of CSS rules at the top. Then every single table row repeats the same CSS as inline styles. Really. Why? No wonder their lines are more than 1,000 characters long.

So, are people intentionally creating HTML with no line breaks to save space? Because if so, CSS rule spam is the opposite of saving space.

---
Tags: 8, emails
---


# Question
Title: Get dynamically created image URL in a block with paragraph and media bundle
I have seen a lot of related answers to this question but nothing specific to my issue - apologies in advance if it has already been answered.

In Drupal 8, I have a custom block type that references a Paragraph type. The Paragraph has a field that references an image media bundle. So it looks something like this:

Block-\> ReferenceFieldForParagraph-\> Paragraph-\> ReferenceFieldForMediaBundle-\> MediaBundle-\> ImageUploadField

I need to apply various image styles to that image and then get the URL for each image.

* In the Paragraph's Display, I have set the field that references the media bundle to display Thumbnail: Original Image
* I have created a twig template for the paragraph bundle and I am able to generate my various images by doing the following:

The media bundle reference field is named field\_slide\_image:

```
{% block paragraph %}
  {% block content %}

    {# set the styles #}
    {% set image1 = content.field_slide_image.0|merge({'#image_style': 'style1'}) %}
    {% set image2 = content.field_slide_image.0|merge({'#image_style': 'style2'}) %}
    {% set image3 = content.field_slide_image.0|merge({'#image_style': 'style3'}) %}

    {# render images #}
    {{ image1 }}
    {{ image2 }}
    {{ image3 }}

  {% endblock %}
{% endblock paragraph %}

```

I cannot figure out how to get the URL. I have tried to use file\_url() but I don't see any reference to the uri when I use kint. In other words, something like this doesn't work:

```
{% set image1 = content.field_slide_image.0|merge({'#image_style': 'style1'}) %}
{% set uri1 = file_url(image1.uri.value)  %}
{{ uri1 }}

```

I need the url's so that I can create a custom responsive image using the picture tag. I need to generate this dynamically because I have another field (select box) that specifies the dimensions of the images (ie the image styles). For example, option 1 is a 1x1 ratio, option 2 is a 3x4 ratio, etc. I could easily print all images and set up media queries to hide/display them but I don't want to resort to that if I don't have to.

Here is what I see when I kint image1

Thanks in advance

# Answer
I wouldn't try to hack the render array `content`. You might be more successful with the `paragraph` entity:

```
{% set uri = paragraph.field_slide_image.0.entity.field_image_upload.entity.uri.value %}

{% set url1 = uri|image_style('style1') %}
{% set url2 = uri|image_style('style2') %}
{% set url3 = uri|image_style('style3') %}

```

For the filter `image_style` install the module Twig Tweak.
> 1 votes

---
Tags: theming, uri
---


# Question
Title: Drupal 8 migrating image from local folder per XML file
I'm trying on this for two days now and I don't get it. I need some more experienced people to look over my code. This is my first Drupal 8 project, meaning, Drupal 8, Twig, Migration API, Yaml... it's a lot of new stuff for me and I'm still learning.

I need to import data from a XML file. I wrote a custom module and was able to migrate all the XML nodes into D8 nodes, but only text fields and taxonomy terms.

There are also image references in some XML nodes and I know, I have to migrate them first into file entities before referencing them in the nodes. So I wrote a second migrate configuration, but it doesn't work and I'm stranded. I don't find a mistake in my yml file, it's close to this example on GitHub: drupal-migration-example

My source data folder, containing some jpgs and a XML file, is stored inside the public file folder.

Maybe important for my issue: Not every XML node has an image reference. But I think I catch that with plugin: skip\_row\_if\_not\_set. I don't know how to debug that.

What I have so far:

```
id: clio_cover_import
label: Clio-Cover-Import
migration_group: werk_import
# Source
source:
  # XML data parser
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: xml
  urls: public://import/werk-import.xml
  item_selector: /Werke/Werk
  fields:
    -
      name: clio_cover
      label: 'Werk-Cover'
      selector: Coverpath
  ids:
    clio_cover:
      type: string
  constants:
    file_source_uri: public://import
    file_dest_uri: 'public://cover_uploads'
# Destination
destination:
  plugin: 'entity:file'
#Mappings
process:
  settings:
     # Check if the "clio_cover" key exists in the "data" array.
     plugin: skip_row_if_not_set
     index: clio_cover
     source: data
     message: "Missed the 'data' key"
  file_source:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_source_uri
        - clio_cover
    -
      plugin: urlencode
  file_dest:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_dest_uri
        - clio_cover
    -
      plugin: urlencode
  uid:
    plugin: default_value
    default_value: '1'
  filemime:
    plugin: default_value
    default_value: 'image/jpeg'
  status:
    plugin: default_value
    default_value: '1'
  filename: clio_cover
  uri:
    plugin: file_copy
    source:
      - '@file_source'
      - '@file_dest'
# Dependencies
dependencies:
  enforced:
    module:
      - clio_import_modul
migration_dependencies:
  required: {}
  optional: {}

```

Every help is very appreciated!

# Answer
> 2 votes
Thanks to quietone, I figured it out. The settings for skipping row didn't work as expected. Instead of repairing, it's much easier for me to modify the XML-file and remove all rows without image node.

So I don't need the skipping plugin anymore and can change the process part to this (and it's working):

```
process:
  file_source:
  -
    plugin: concat
    delimiter: /
    source:
      - constants/file_source_uri
      - clio_cover
  file_dest:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_dest_uri
        - clio_cover
  uid:
    plugin: default_value
    default_value: '1'
  uri:
    plugin: file_copy
    source:
      - '@file_source'
      - '@file_dest'
  filename: clio_cover_name

```

# Answer
> 0 votes
Things to check are the migrate tables, migrate\_map\_clio\_cover\_import and migrate\_message\_clio\_cover\_import. The latter table can be seen with `drush mmsg clio_cover_import`. The message table will have a message for every row skipped which may determine if the skip on the settings property is working as you expect.

Also, check the file\_managed table.

Apologies if you've done these already.

---
Tags: migrations
---


title: Rules module user/register

text:
# Question
Title: Rules module user/register
I keep getting spammed/attacked looking at reports/db. Anonymous users keep trying to go to `/user/register` (but I disabled registering). So being annoyed by anons still trying to going to that url, I decided to write a rule:

```
{ "rules_anon" : {
"LABEL" : "Anon",
"PLUGIN" : "reaction rule",
"WEIGHT" : "-10",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_view" : [] },
"IF" : [
  { "user_has_role" : {
      "account" : [ "site:current-user" ],
      "roles" : { "value" : { "1" : "1" } }
    }
  },
  { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "user\/register" } }
],
"DO" : [ { "redirect" : { "url" : "node\/39" } } ]}}

```

Context: Node 39 is Page Not Found

I tried it and it did not work, gives me `do not have access` message. So I tried the rule for a different url (/about) and it worked. I am guessing that url `/user/register` has a special case where Rules can not override it.

My question is: is there a way to redirect anonymous users from `/user/register` ?

# Answer
Whatever you want to happen via Rules module when some link is clicked, if you're using Rules Event '`Content is viewed`', you'll probably be too late:

* the content (or whatever the clicked link is about) is already being shown, so if the Rules Conditions are satisfied, the Rules Actions will be performed. That is what 'Content is viewed' is all about.
* if you didn't want to content (or whatever the clicked link is about) to be visible at all, well sorry, but you're too late.

If however you did want something to happen BEFORE showing the content (or whatever the clicked link leads to), then you should use Rules Event '`Drupal is initializing`'. Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for way more details on this.

**Attention**: Rules Event '`Drupal is initializing`' gets triggered on every (repeat: every) page load in a Drupal site. So for performance reasons, you really want to limit the number of active Rules that use this Rules Event to an absolute minimum, i.e. as your last resort (if anything else fails).
> 2 votes

---
Tags: users, rules, advertising
---


# Question
Title: Each node has a score (percentage) which is updated weekly & want to show latest and the past scores in below/in a chart
The site is keeping scores (by percentage) of how well it does in a certain area. So each node is a different area and that node will have a score of 7% in week 1. An example: Liverpool's score is 11.23% for week 1 of 2018, week 2 that node (Liverpool) is updated and it gets a score of 12.01%, etc, etc.

In week 2, we update that nodes score to 9.5%, I want to show this prominently at the top of the page as the current score. Then underneath, show a chart of the previous scores or at least at the very minimum show all the scores in a neat line, going back/down in order of date.

I then also want to show all of these nodes (areas) in one view, showing in a ranking list, this would just be a view?

Is this the right way to go about it, with nodes that are updated/revisions? Or am I thinking about this all wrong?

What about using table field for the past scores and just having the current score as it's own field shown at the top?

# Answer
You could implement them with a field\_collection (currently not stable for either D7 or D8) or with the paragraphs module (currently stable for D8 only) if you need to keep track of old scores of each node and when they've been set.

I've also implemented similar things (paired values) by simply having two multivalue fields, one after the other, and letting editors keep them in sync manually, then rendering them together in a table or the alike with a custom template.

Using two simple multivalue fields (and they could be both numeric fields, if the time is something simple as the number of the week) may eventually simplify accessing such data in a view.
> 1 votes

---
Tags: nodes, charts
---


# Question
Title: How to Set Hidden Form Field Values Permanently via Form Alter
I have a webform that gets some hidden form fields set based on the referring URL. Within hook\_form\_alter, I can successfully set the hidden values with $form\[elements\]\[NAME\]\['#value'\].

```
function MODULE_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

 //Get referring Program path/URL
 $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');

 if ($form_id == FORM_ID) {

    $prog = getLeadProgramContact($previousUrl);
    $form['elements']['referrer']['#value'] = $prog->field_email->value;
    $form['elements']['program_name']['#value'] = $prog->getName();
     }
}

```

However, when the form gets submitted, it appears hook\_form\_alter is called again, breaking everything, since the referring URL is now itself.

How can I permanently set hidden field values on initial form render? Anything I try with hook\_form\_alter seems to fail. I have also tried "#default\_value"

# Answer
Ok webforms are a bit tricky ... but this will work i don't really care to set hidden fields just set the data direct to the entity.

if this is not a multy step form you could probably ad another submit handler in your form alter aka ...

```
function MODULE_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
   if ($form_id === FORM_ID) {
     $submit[] = 'MODULE_form_alter_submit';
  }
}
// then
function MODULE_form_alter_submit(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
     // get the data you need.. via this ..
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    $prog = getLeadProgramContact($previousUrl);
    // or ($_GET) or session or cookie whatever you chose.. Then set    it

    // GET the form Object.
    $webform_submission_object = $form_state->getFormObject();
    // GET the submission object.
    $webform_submission = $webform_submission_object->getEntity();
    // Optioanl default values if need to play with them ..
    $orig_data = $webform_submission->getOriginalData();
    // set form state
    $form_state->setValue('referrer', $prog->...);
    // set submission field value.
    $webform_submission->setElementData('referrer', $value);

    $form_state->setValue('program_name', $prog->...);
    $webform_submission->setElementData('program_name', $value);
    // Save it so it cant go away.
    $webform_submission->save();

  }
 }
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: Commerce Kickstart Review Overrides Error
I want to upgrade Commerce Kickstart (commerce\_kickstart-7.x-2.53) to the latest 2.54. Following the upgrade instructions I went to the Structure Features menu to check for overrides and found these are overriden.

```
Commerce Kickstart Blog
Commerce Kickstart Lite Product
Commerce Kickstart Merchandising
Commerce Kickstart Slideshow
Commerce Kickstart User

```

But when I go to Review Overrides, I get these errors.

```
Notice: Array to string conversion in features_override_features_export_render_addition() (line 428 of /home/-----/public_html/sw/profiles/commerce_kickstart/modules/contrib/features_override/features_override.export.inc).
Notice: Array to string conversion in features_override_features_export_render_addition() (line 428 of /home/-----/public_html/sw/profiles/commerce_kickstart/modules/contrib/features_override/features_override.export.inc).
Error: Call to a member function stateVariables() on string in RulesPlugin->availableVariables() (line 740 of /home/-----/public_html/sw/profiles/commerce_kickstart/modules/contrib/rules/includes/rules.core.inc).

First, is there a fix for these errors?
If not, is there any way to know what overrides are actually in place?
In any case, can I proceed with the Commerce Kickstart (commerce_kickstart-7.x-2.54) upgrade?

```

FYI: Running Drupal 7.58 and PHP Version 7.1.16

Thanks

# Answer
Are you sure those modules are compatible with PHP 7? We haven't tested nor do we recommend running Commerce Kickstart 2.x in PHP 7 as far as I know.
> 0 votes

---
Tags: commerce
---


# Question
Title: Drupal Commerce - Sort products in view priced lowest to highest
This seems like it should be super simple. I'm trying to sort my products by price (from lowest to highest) in my view, and no matter what I do, nothing seems to work. See below the setup of my current view. At the moment, the below settings give me the lower priced products first (e.g. it shows products ranged $4-9 before products ranged $50-90), but they're all mixed up (e.g. $4, $7, $4, $9...) when it should be $4, $4, $7, $9...

I hope that makes sense.

# Answer
It isn't clear to me why you're sorting based on some sort of standard deviation here (or why you're using aggregation at all). If you really just want to sort a list of products by price in a taxonomy term, you should just keep aggregation off and sort on the price directly.

If you need aggregation on, you're going to need to explain the intent behind this sort method.
> 0 votes

---
Tags: 7, views, commerce
---


# Question
Title: Twig's slice filter behaves unusual for non English languages
I have used slice filter to display few number of Japanese alphabets from a sentence.

```
{{ desc|length > 65 ? desc|slice(0, 65) ~ '...' : desc }}

```

But sometimes it slices very early when a Japanese full-stop appears and the preceding sentence has long length for full-stop to appear.

I have 3 patterns to show:

---

1) When I have following text to slice:

> 何もほかけっしてその納得学というののために見なん。ちょうど今に話家はまるでその使用ませですくらいが出ているんがは反抗おっしゃれなけれでて、さらににはなっましましなん。主義にみでのはけっして前を余計でですた。

It slices the above thing as:

> 何もほかけっしてその納得学というののために見なん。

---

2) For following string

> 同時にネルソンさんに自覚文字当然発展のするでがたある馳何か相当がという実お話しませますたならで、この今もあなたか世の中鷹狩を使いこなすので、岡田さんの事に政府の私にもしご意見と云えて私宅にご記念になさいようにどうしてもご話の始めんたて、最も勢い発音へ云わましてならたのを立つないまし。

It slices to:

> 同時にネルソンさんに自覚文字当然発展のするでがたある馳何か相当がという実お話しませますたならで、この今もあなたか世の中鷹狩を使いこ...

which is perfectly sliced to 65 alphabets.

---

3) For following string:

> 教師でしかしネルソン君にまたはそれだけ聞いうのうたう。向さんもさっそく国家をしばした事べくですた。（また考を云っ以上でしょですたてたも間違っあるたらが、）そう好かあり相場を、スコットの冠詞じゃしでみに対して、主義の下宿は前の他まで知れ当る気に行かませて刺戟院叱らて来るですというお自分ないものん。

It slices to:

> 教師でしかしネルソン君にまたはそれだけ聞いうのうたう。向さんもさっそく国家をしばした事べくですた。

---

Is there any way to solve it or any other solution to achieve this?

# Answer
As the trim was enabled from both twig as well as display format, it was not working. So keeping the display format for that field to Default, it solved my issue.

For other users who might face such problem, just keep in mind to set only single trim (either from back end or front end side)
> 2 votes

---
Tags: 8, theming
---


title: field_collection_item_load() Error

text:
# Question
Title: field_collection_item_load() Error
When I use field\_collection\_item\_load() to load the field collection I found this warning again n again.

`Warning: array_flip(): Can only flip STRING and INTEGER values! in EntityAPIController->load() (line 219 of /home/webtesting/public_html/zprimataste/prima-web/sites/all/modules/entity/includes/entity.controller.inc).
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 388 of /home/webtesting/public_html/zprimataste/prima-web/includes/entity.inc).`

Please help

# Answer
> 0 votes
You want to load node? I think below code will do that

```
$entity_id = (int) $node->field_some_collection['und'][0]['value'];
$entities = entity_load('field_collection_item', array($entity_id));

```

Reference https://www.drupal.org/project/field\_collection/issues/1164982

---
Tags: theming
---


# Question
Title: How to debug a variable in a controller class (var_dump)
I am trying to do a var dump from a Drupal 8 Controller class. This is not working because controllers need to send a response. I just need to see the contents of a variable and I have not idea how to do this since I've tried all response combinations and can't seem to get it working.

This is my variable.

```
$storage = \Drupal::entityTypeManager()->getStorage('node');
$node = $storage->load($rep_id);

```

I am trying to `var_dump($node)` to see what's in it. Can anyone help?

# Answer
> 2 votes
You should be able to do this:

```
use Symfony\Component\HttpFoundation\Response;

return new Response('<pre>' . var_export($node, TRUE) . '</pre>');

```

# Answer
> 3 votes
OK, I'm going to be *that guy.* Do yourself a favour and set up Xdebug, hacks like var\_dump() or var\_export() are very bad practice and sooner or later you will forget to remove some of those statements and it will end up in production. Also it takes one single click to set up a breakpoint, as opposed to writing a var\_dump() or var\_export() statement. Not to mention that the amount of information you can get by using a debugger is vastly more comprehensive.

# Answer
> 2 votes
While there's a few options, you could try:

```
drupal_set_message('<pre>' . var_export($node, 1) . '</pre>');

```

# Answer
> 1 votes
These are some other techniques:

**1\] Debug**

* Drupal core comes with its own function debug()

**2\] Devel**

* intstall `composer require symfony/var-dumper`
* clear cache with UI or `drush cr`
* at devel settings page set var-dumper as a default option
* use devel functions `dpm()` `kpr()` for inspecting variables in your code
* `{{ devel_dump() }}`, `{{ kpr() }}` or `{{ dpm() }}` in twig templates

**3\] Other contributed modules**

**Note:** (Read Jaypan's answer) You can also use PHP's native functions like `var_dump` or `print_r`

---
Tags: nodes, debugging, page-controller
---


# Question
Title: How to configure my local Drupal site to contact my local Apache Solr server?
I installed Apache Solr server on my local machine and installed the Apache Solr Search module on my Drupal 7 site. When I configure the module and click submit an error message appears:

> Your site was unable to contact the Apache Solr server.

But when I go to http://localhost:8983/solr/#/ my Solr admin opens.

# Answer
You haven't added any cores to Solr and you need to add at least one core and adjust the connection properties.

You will probably need the Solr 7 config from Search API Solr Search, as Apache Solr Search only has config for 5.x. The commands you need to run are: (replace CORE with the actual name)

1. `cd /opt/solr/server/solr`
2. `sudo mkdir -p CORE/conf`
3. `sudo cp -R search_api_solr/solr-conf/7.x/* CORE/conf`
4. `cd /opt/solr`
5. `sudo -u solr ./bin/solr create -c CORE -d server/solr/CORE/conf`

This should take the config files and create a core with those files. Then adjust your connection to http://localhost:8983/solr/CORE
> 1 votes

---
Tags: search
---


# Question
Title: How to automatically enable custom modules upon theme activation?
I have a custom module that I have defined in the `[root]/modules/[custom module]` directory. I want it to get activated as soon as someone installs my theme rather than handing over user the custom modules folder and asking to manually install that module one by one via the Extend option on the dashboard. How can we get that done in Drupal 8?

# Answer
As @4k4 mentioned there's ongoing development to Allow themes to declare dependencies on modules which hopefully lands in core with 8.6.0. Until then you are a little bit out of luck, except you find a place somewhere in your theme to trigger the following line of code:

```
\Drupal::service('module_installer')->install(['MYMODULE']);

```

Alternatively you could **provide a second module** which **provides some button in the back-end** which on-click triggers **the above line PLUS the following two lines** all at the same time.

```
\Drupal::service('theme_installer')->install(['MYTHEME']);
\Drupal::service('theme_handler')->setDefault('MYTHEME');

```

---

The background behind the issue mentioned above is that themes can't provide Drush 9 commands. As Drush 9 commands depend on certain services. But themes ain't allowed to provide these services. See the following issue: Allow themes to provide services.yml which was closed as *won't fix*.

The reason to close the service-issue (in a nutshell) is to keep things clean (from an OOP point of view) and don't let themes become *other* modules. Themes should provide templates, styles, scripts. Whereas modules should provide everything OOP-related, including services.

And as themes now (because of this decision) can't provide Drush commands anymore there must be away to allow them to rely on companion modules to provide useful commands/scripts and libraries for (sub-)theme development and maintenance. Which then will probably get activated automatically upon theme activation. So let's look forward and contribute to get this into core ASAP!
> 2 votes

---
Tags: 8, installation
---


title: Send email to users after node update

text:
# Question
Title: Send email to users after node update
I have a content type "Room" with this config:

* Title
* Body
* field\_comments (Comments)
* field\_members (Users Entity reference)

When I create a room I send with hook\_entity\_insert() an email to users add to the room

But my problem is when I edit this room and I add New members, I want to send an email only for new.

I try it with this code in custom module with hook\_entity\_update:

```
notify.module
/**
* Implements hook_entity_update().
*/
function notify_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
 if ($entity->getEntityTypeId() !== 'node' || ($entity->getEntityTypeId() === 'node' && $entity->bundle() !== 'room')) {
   return;
 }
 $mailManager = \Drupal::service('plugin.manager.mail');
 $module = ‘notify’;
 $key = 'new_notif';

 //send to all members in room
 $members = $entity->get('field_members')->getValue();
    $tos = [];
    foreach ( $members as $member ) {
        if ($member['target_id'] !== '1') {
            $tid = intval($member['target_id']);
            $user = \Drupal\user\Entity\User::load( $tid );
            $tos[] = $user->getEmail();
        }
    }

 $membersTo = implode (', ', $tos);

 $to = $membersTo;

 $params['message'] = 'You access to the room';

 $params['node_title'] = $entity->label();
 $langcode = \Drupal::currentUser()->getPreferredLangcode();
 $send = true;
 $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
 if ($result['result'] !== true) {
   drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
 }
 else {
   drupal_set_message(t('Your message has been sent.'));
 }
}

```

I Don't know how to exclude old members after edit, add new members and save a room.

# Answer
> But my problem is when I edit this room and I add New members, I want to send an email only for new.

As hook\_entity\_update mentions

> Get the original entity object from **$entity-\>original**.

`$entity->original` gives you access to the values before the update.

So all you gotta do is compare the original members to the updated members to find out who are the new members.

```
$og_members = array();
$og_members = $entity->original->get('field_members')->getValue();

$up_members = array();
$up_members = $entity->get('field_members')->getValue();

$new_members = array();
// use array_diff() to find the difference.
$new_members = array_diff($up_members, $og_members);

```
> 2 votes

# Answer
Ok you have options here...

Option1, (Harder) If the node revisionable ... you can do a difference check between the last revision and the newly added values ...

Option 2 (easy)

make a new field called field\_members\_to\_add (Users Entity reference) when you edit the node you would put the new people on the new field ... then in your "hook\_entity\_update" you can get the values of this field.. send the emails, update the normal "field\_members" with the new values .. then set "field\_members\_to\_add" it to null so it will be empty next time you add new people.

so then it would be...

```
  $new_members = $entity->get('field_members_to_add')->getValue();
  // send email ...then later...
  $entity->set('field_members_to_add', NULL);
  $old_members = $entity->get('field_members')->getValue();
  // merge values.
  $all_members = array_merge($old_members,$new_members);
  $entity->set('field_members', $all_members);
  // Party.

```
> 0 votes

---
Tags: 8, nodes, emails
---


# Question
Title: Avoid undelivered mail returned to sender
I have a webform that sends emails to the user who completes it. When the wrong email address is entered, I receive an email whose subject is *Undelivered Mail Returned to Sender*.

How can I avoid it? I don't see any parameter in the webform configuration.

# Answer
Have to admit that I'm not familiair with webforms but is it possible that you send the e-mail from a noreply mail? This way you don't have to read the inbox of this mail address.
> 0 votes

---
Tags: webforms, emails
---


title: How to Override Views Field Handler

text:
# Question
Title: How to Override Views Field Handler
Is it possible to overwrite a Views Field hander without creating a new field?

For example, I am trying to overwrite the Geolocation ProximityField field handler.

```
<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\geolocation\Plugin\views\field\ProximityField;
use Drupal\Core\Form\FormStateInterface;

/**
 * Field handler for geolocation field.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("geolocation_field_proximity")
 */
class RangeProximityField extends ProximityField {

  /**
   * Form constructor for the user input form.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function viewsForm(array &$form, FormStateInterface $form_state) {
    $this->viewsForm($form, $form_state);
    // Add custom logic here.
  }

}

```

I tried using hook\_views\_data\_alter() but had no luck (I renamed in above annotation to mymodule\_field\_range\_proximity):

```
/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(array &$data) {
  $data['node__field_latlong']['field_latlong']['field']['id'] = 'mymodule_field_range_proximity';
}

```

# Answer
You don't need to create a new field handler. You can replace the class of the existing field plugin. The plugin manager provides a hook to alter the plugin definitions:

```
/**
 * Implements hook_views_plugins_field_alter().
 */
function mymodule_views_plugins_field_alter(array &$plugins) {
  $plugins['geolocation_field_proximity']['class'] = 'Drupal\mymodule\Plugin\views\field\RangeProximityField';
}

```
> 7 votes

# Answer
Instead of trying to altering that field I just created a new field formatter.

```
/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(array &$data) {
  $data['node']['mymodule_field_proximity_range'] = array(
    'title' => t('Proximity Filter with Range'),
    'field' => array(
      'title' => t('Proximity Filter with Range'),
      'help' => t('Proximity Filter with Range'),
      'id' => 'mymodule_field_proximity_range',
    ),
  );
}

```
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Unable to install the “H5P.Scorm.h5p” library: “The uploaded file was not a valid h5p package”
Thanks to jackrabbithanna’s help on this other question I seem to be 1/2 way to getting H5P related libraries installed in my Drupal 7.59 install. I am attempting this on macOS High Sierra under MAMP 4.5 (PHP 7.1.12) and MAMP 3.5.2 (PHP 5.6.10).

But like I said, I am 1/2 way there; not fully there. I am able to get the `H5PEditor.ScormFile (1.0.8)` library installed, but not `H5P.Scorm (1.1.16)`.

The libraries in question are as follows:

To help this process, I have now devised a bit of a Bash scripting process to get the `h5p` packages built from the source GitHub repos. Here is what I do…

### The `H5PEditor.ScormFile (1.0.8)` Bash dance:

```
cd ~/Desktop/

git clone https://github.com/pavloshevchuk/h5p-editor-scorm

cd ~/Desktop/h5p-editor-scorm

find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

mkdir H5PEditor.ScormFile && mv {scripts,styles,*.json} H5PEditor.ScormFile

echo '{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5PEditor.ScormFile",
      "majorVersion": 1,
      "minorVersion": 0,
      "patchVersion": 8
    }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}' > h5p.json

zip -r ../H5PEditor.ScormFile.h5p *

```

### The `H5P.Scorm (1.1.16)` Bash dance:

```
cd ~/Desktop/

git clone https://github.com/pavloshevchuk/h5p-scorm

cd ~/Desktop/h5p-scorm

find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

mkdir H5P.Scorm && mv {css,js,*.json} H5P.Scorm
mkdir content && mv icon.svg content

echo '{
  "title": "SCORM/xAPI",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5P.Scorm",
      "majorVersion": 1,
      "minorVersion": 1,
      "patchVersion": 16
    }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": [
    "div"
  ]
}' > h5p.json

zip -r ../H5P.Scorm.h5p *

```

And with those two things done I now have two H5P files ready to go: `H5PEditor.ScormFile.h5p` and `H5PEditor.ScormFile.h5p`.

But while installing `H5PEditor.ScormFile.h5p` proceeds as expected, the same can’t be said for `H5PEditor.ScormFile.h5p`. I get the following Drupal system information message:

> For security reasons, your upload has been renamed to H5P.Scorm\_.h5p.

Followed by this “great news”:

> The uploaded file was not a valid h5p package

Screenshot attached below. Any insight is appreciated.

# Answer
> 1 votes
### Short Answer

Font Awesome (4.5.4) libraries needed to be explicitly installed for H5P so that Scorm (1.1.16) can be installed. Details on how that was done near end of answer.

---

### Long Answer

Happily, I was able to self-solve this. Starting with a fresh, clean, 100% new install of Drupal 7.59 I went ahead with this process again. Getting `H5PEditor.ScormFile (1.0.8)` installed was fine—as before on a more established Drupal 7.59 install—but ran into the same exact issue with `H5P.Scorm (1.1.16)`… But on this clean install I did get a major clue via more details in error reporting; screenshot below but the text reads:

> “Missing required library FontAwesome 4.5”

I took this error to mean that the Drupal module and related libraries for Font Awesome were not installed and that is why the “The uploaded file was not a valid h5p package.” error came up.

So I went ahead and did that—and installed Font Awesome 4.7 libraries—screenshot below:

Tried installing `H5P.Scorm (1.1.16)` again… And again, the same message:

> “Missing required library FontAwesome 4.5” message.

So I took this all to mean that H5P needed it’s own library install of Font Awesome, Googled and found this H5P related Font Awesome repo.

Great! So now learning what I learned previously in this other answer, I figured out how to create my own `H5P.FontAwesome.h5p` library, which WORKS GREAT! Screenshot below to show the process did work and I was able to get `H5P.Scorm (1.1.16)` installed once the H5P specific Font Awesome library was installed as well:

And to make everyone’s life easier—especially mine—I created a fairly simple Bash script that allows me to automatically create the `H5PEditor.ScormFile.h5p`, `H5P.FontAwesome.h5p` and `H5P.Scorm.h5p` libraries on my macOS machine; see below for source code. Just save it as a Bash file named something like `build_h5p_scorm_libs.sh` and give yourself execute permissions via `chmod u+x build_h5p_scorm_libs.sh` and you are good to go.

Library installation order should be as follows:

* `H5PEditor.ScormFile.h5p`
* `H5P.FontAwesome.h5p`
* `H5P.Scorm.h5p`

Genuinely hope this helps someone in the future!

```
#/bin/bash

################################################################################
# Build the H5PEditor.ScormFile H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/pavloshevchuk/h5p-editor-scorm

# Go into that cloned repo.
cd ~/Desktop/h5p-editor-scorm

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir H5PEditor.ScormFile && mv {scripts,styles,*.json} H5PEditor.ScormFile

# Create the 'h5p.json' file.
echo '{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5PEditor.ScormFile",
      "majorVersion": 1,
      "minorVersion": 0,
      "patchVersion": 8
    }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5PEditor.ScormFile.h5p *

################################################################################
# Build the H5P.FontAwesome H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/h5p/font-awesome

# Go into that cloned repo.
cd ~/Desktop/font-awesome

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir FontAwesome && mv {*.css,*.otf,*.eot,*.svg,*.ttf,*.woff*,*.json} FontAwesome

# Create the 'h5p.json' file.
echo '{
  "title": "FontAwesome",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "FontAwesome",
      "majorVersion": 4,
      "minorVersion": 5,
      "patchVersion": 4
    }
  ],
  "mainLibrary": "FontAwesome"
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5P.FontAwesome.h5p *

################################################################################
# Build the H5P.Scorm H5P file.
################################################################################

# Go to the Desktop.
cd ~/Desktop/

# Clone the repo.
git clone https://github.com/pavloshevchuk/h5p-scorm

# Go into that cloned repo.
cd ~/Desktop/h5p-scorm

# Clean up cruft that is not needed for the H5P file.
find . -type f \( -name '.DS_Store' -o -name '.gitignore' -o -name 'LICENSE' -o -name 'README.md' \) -exec rm {} \;
find . -type d -name '.git' -exec rm -rf {} \;

# Create the library directory and copy files into it.
mkdir H5P.Scorm && mv {css,js,*.json} H5P.Scorm

# Create the content directory and copy files into it.
mkdir content && mv icon.svg content

echo '{
  "title": "SCORM/xAPI",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    {
      "machineName": "H5P.Scorm",
      "majorVersion": 1,
      "minorVersion": 1,
      "patchVersion": 16
    }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": [
    "div"
  ]
}' > h5p.json

# Now Zip that all up into a compressed `.h5p` archive like this.
zip -rq ../H5P.Scorm.h5p *

```

---
Tags: 7
---


# Question
Title: Getting average of a numerical field across multiple nodes
I have a node type with a decimal field on it that saves percentages from 0-100%.

I want to get the average percentage from across all the nodes in that node type. So that no matter how many nodes are created under that node type, I can show the average on a landing page elsewhere using views.

Using drupal 8 and struggling to get this working.

# Answer
Follow these instructions:

1. Open your view in edit mode.
2. Open the **Advanced** tab.
3. Find the section named **Other**
4. Enable the **Use aggregation** option
5. Click on the **Aggregation settings** option for your desired field
6. Select **Average** from **Aggregation type** select list
> 1 votes

---
Tags: views
---


title: Testing field value in twig template

text:
# Question
Title: Testing field value in twig template
In my twig theme - I'm attempting to test the value of the field "field\_left\_image\_front" - which is either "Yes" or "No"

```
{% if content.field_left_image_front.0 == "Yes"  %}
<img class="content-image" src="{{ file_url(content.field_left_image.0['#item'].entity.uri.value) }}">
{% else %}
<div class="textdescriptions" style="background-color:{{ content.field_left_hex_color.0 }}"><!--start text descriptions-->
<div class="textdetails" style="color:white !important"> <!--start text details-->
<h1>{{ content.field_left_title.0 }} {{ content.field_left_image_front.0 }}</h1>
<p>{{ content.field_left_body }}</p>
</div><!--end text details-->
</div>
{% endif %}

```

A few bits of info:

1. field\_left\_image\_front is a select list/list item in the CMS
2. I'm testing the value by outputting it in h1 tag - so I can see that it's "Yes"
3. Despite being "Yes", it's outpitting the text description and ignoring the image.

Is there something I'm doing wrong with the conditional?

# Answer
> 1 votes
Use `node` (if this is a node template) to get the field value, see Conditional statement doesn't work in node.html.twig. Another reason in this case is that Yes/No would be translatable in a multilingual site, while the field value from `node`is the untranslatable left key of a select list.

If it is not a node template look at the variables listed at the top of the template, for example paragraph.html.twig:

```
/**
 * @file
 * Default theme implementation to display a paragraph.
 *
 * Available variables:
 * - paragraph: Full paragraph entity.

 * - content: All paragraph items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.

```

Here the variable for the entity is `paragraph` and for the render array `content`.

So use `{{ content.field_example }}` to print fields and `{{ paragraph.field_example.value }}` to get field values from the database.

---
Tags: 8, theming
---


# Question
Title: Dealing with node language when manually updating node
I'm trying to manually update a node and I'm not sure how the language works.

The node is in English, so `$node->language = 'en';`

However, all my fields data are organized like this in the node:

```
$node->field_name['und'][0]['value']

```

I thought `'und'` means "language undefined", so shouldn't it be `'en'` instead?

I'm trying to automate the process so is it safe to assume fields will always use `'und'` in nodes?

# Answer
> 4 votes
Yes - it is safe to assume this. The locale module will deal with this by setting it to the language code of the default language, ex 'en'.

Citing from: http://drupal.org/update/modules/6/7#drupal\_language\_none

```
In Drupal 7, the LANGUAGE_NONE constant should be used for nodes or other items that do not have a specific language associated with it.

http://api.drupal.org/api/drupal/includes--bootstrap.inc/constant/LANGUAGE_NONE/7

```

# Answer
> 0 votes
You can get field values without use LANGUAGE\_NONE.

```
$field_items = field_get_items('node', $node, 'field_name');
$value = $field_items[0]['value'];

```

# Answer
> -1 votes
Instead of specifying a language, I prefer to just use `entity_metadata_wrapper()`.

For example:

```
$node = entity_metadata_wrapper('node', SOME_NODE_ID);
$value = $node->field_something->value(); // returns field value
$node->field_something->set('new value'); // sets field value
$node->save();

```

Source: https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers

---
Tags: 7, nodes, i18n-l10n
---


# Question
Title: How are the templates in the js_example module retrieved?
I installed js\_example, one of the sample modules in the Examples for Developers module.

In this module I found the following configuration:

```
css
 - jsweights.js
js
 - black.js
 - blue.js
 - brown.js
 - green.js
 - js_example_accordion.js
 - purple.js
 - red.js
src
 Controller
  - JsExampleController
templates
 - accordion.html.twig
 - description.html.twig
js_example.info.yml
js_example.libraries.yml
js_example.links.menu.yml
js_example.module
js_example.routing.yml

```

I do not understand how the template `description.html.twig` and `accordion.html.twig` are retrieved.

I miss this piece to understand the example completely.

In which file do I find the configuration I am looking for?

# Answer
Inside `js_example.module` there's a function which declares how a render array using a certain `'#theme'` is to be rendered as HTML and which variables might be available. This function is `hook_theme`. It also can define a template that Drupal will look for inside the module's `template` folder.

```
function js_example_theme() {

  return [
    'js_example_accordion' => [
      'template' => 'accordion',
      'variables' => [
        'title' => NULL,
      ],
    ],
  ];
}

```

Next there is the `src/Controller/JsExampleController.php` which has a function to output stuff and is told to use the `'js_example_accordion'`-`'#theme'` for that.

```
  public function getJsAccordionImplementation() {

    $title = $this->t('Click sections to expand or collapse:');

    $build['myelement'] = [
      '#theme' => 'js_example_accordion',
      '#title' => $title,
    ];

    $build['myelement']['#attached']['library'][] = 'js_example/js_example.accordion';

    return $build;
  }

```

That's the basics.

---

The `description.html.twig` is used a little bit differently but maybe just skip that for now as its some kind of advanced exception you'll understand later.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Setting date_popup year range to more than the 3 years default in Drupal 7
I have a custom module and using date\_popup. Currently the popup only shows a 3 year range in the date popup.

```
  $form['startdate'] = array(
    '#type'       =>  'date_popup',
    '#title'      =>  'From',
    '#default_value'  =>  filter_get('browse-startdate'),
    '#date_format'    =>  'Y-m-d',
  );

```

What is needed to make the range higher?

# Answer
Use the following option in the array:

```
    '#date_year_range' => '-8:+8'

```

That goes up to 8 years or more. Generally you don't use minDate as that only goes back up to 3 years only.
> 6 votes

# Answer
If it doesn't work backend wise like in my case (embedding user\_register\_form with date fields inside a custom build multistep form), you can alter these settings in javascript :

```
var fixDatepickerYearRange = function() {
        $('.field-widget-date-popup').find("input").datepicker({
          yearRange: "-100:+0",
          changeMonth: true,
          changeYear: true,
          dateFormat: "dd/mm/yy"
        });
      };

```

Just run it from document.load or Drupal.behaviors. More info : http://api.jqueryui.com/datepicker/#option-yearRange
> 0 votes

---
Tags: 7, forms, datetime, javascript
---


# Question
Title: Display block if content type has entity reference (tags) that contains specific term
I want to display a block when a node contains a entity reference field when specific term is present.

I have tried numerous modules that did not work for me or perhaps I did not set them up right, term\_condition token\_conditions entity\_field\_condition (using the appropriate patch)

EDIT: it seems the term\_condition works on a clean install after applying some pending patches on the issue queue. So this probably is a problem with my installation.

# Answer
The easiest solution is probably term\_condition

Install/enable the module and then on the block layout of a certain block you will be presented with a *term visibility setting* where you can search for term that will be used as the visibility condition.

**NOTE:** Currently the module is incompatible with rules as rules has its numerous conditions on its own. This issue has been reported here
> 0 votes

---
Tags: 8, blocks
---


title: User registration through service

text:
# Question
Title: User registration through service
I have a local Drupal instance with services. I created an endpoint that has user resource included. I verified that all is well by logging in using the endpoint. I am now stuck at registering new users through the api. I tried the following:

URL: http://localhost/recipes/api/user/register

Method: POST

Content-Type: application/json

Body: { "name":"user34", "pass":"3323", "mail":"sample@example.com", "status":"1" }

Result: 22:CSRF validation failed

I know that this error pops out when the token is not passed in the header of the request but how am I supposed to get the token if I am an anonymous user wanting to register?

Kindly mention the steps that I need to follow to have a user register through the REST api

Thanks :)

# Answer
Anonymous (and authenticated) users can both get the token from the same place. Try following these steps:

1. Get the token with a `GET` to `?q=services/session/token`
2. Attach the token to your `POST` header under the name `X-CSRF-Token`
3. Make the `POST` call to register the user
> 0 votes

---
Tags: users, services
---