# Question
Title: How do I add a confirmation form after the user clicks on "Save" in an edit form?
On a site I'm building, a user can edit certain fields on a node that cause a chain reaction to happen (which I've implemented using `hook_nodeapi()` and its "update" operation).

Since this chain reaction potentially affects a lot of other content, I'd like to inform the user of exactly what other content will be changed, which depends on the changed field values, unknow until the user submits the node. After the user has read the list of affected content, I'd like to give them the option to click on *Yes*, which will save the node and start the chain reaction, or click *No*, which will take them back to the node edit form (with edits intact).

How can I make a confirmation form appear after the user clicks on *Save*?

# Answer
In brief, this is what I think you need to do in a custom module:

1. After validation, override the submit function on the node form to submit to a new interstitial page (you'll need to implement hook\_menu to create the new page)
2. Pass the node object to the new interstitial page and define whatever logic you need in the interstitial page's callback function.
3. Create a new form on the interstitial page that runs node\_save on submit with node object that was passed to it.
> 0 votes

# Answer
Add javascript function as shown below and then call that function on submit using hook\_form\_alter. This is working for me.

```
/* Javascript Function */
function confirm_reg(val){
var elem = $(this).closest('#'+val);
$.confirm({
    'title'     : 'Confirmation',
    'message'   : 'Are you sure to submit the details ?',
    'buttons'   : {
        'Yes'   : {
            'class' : 'blue',
            'action': function(){
                $("#your_form_id").submit();
                return true;
            }
        },
        'No'    : {
            'class' : 'gray',
            'action': function(){
                return false;
            }   // Nothing to do in this case. You can as well omit the action property.
        }
    }
});
}
 /* hook_form_alter */
 function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
 global $user;
 if ($form_id == "your_form_id") {
    $form['submit']['#attributes'] = array('onclick' => 'if(!confirm_reg(this.id)){return false;}');
 }

```
> 0 votes

---
Tags: 6, nodes, forms
---


title: Annotations without class import?

text:
# Question
Title: Annotations without class import?
The idea of annotations in Drupal 8 is that annotations names map to classes. E.g. `@ViewsRow` -\> `\Drupal\Views\Annotation\ViewsRow`.

From other code I have seen (Symfony, Doctrine), I assumed that to make this work, the annotation class needs to be imported, e.g.

```
use Drupal\Views\Annotation\ViewsRow;

```

However, this seems not to be the case for many of the plugin annotations e.g. in Views.

Why? Is this a Drupalism, or would we find the same in some places in Doctrine or Symfony? Is it good practice to omit the import?

In the past I disliked the need for such use statements, because they would show up in the IDE as "unused import". However, now I am using the annotation plugin in PhpStorm, so now it recognizes those imports.

# Answer
> 5 votes
Drupal's annotation system is based on the Doctrine PHP library, and not on Symfony like the rest of Drupal.

Doctrine uses a global annotation registry to map classes to files (rather than an autoloader). This page contains the list of classes in that registry.

This issue from 2013 shows the Drupal maintainers' decision to remove the need to import annotation classes.

You wouldn't know this by looking at the official Drupal documentation -- they say the annotation classes are loaded "magically".

---
Tags: 8
---


# Question
Title: Set value of a webform field programatically
I am using a custom block in which all nodes of a specific type are loaded and then a webform is loaded and attached to each of these nodes. The webform has a hidden textfield field which I am trying to programatically set to the id of the parent node:

```
class CustomBlock extends BlockBase {

  public function build() {
    // Load all nodes
    $query = \Drupal::entityQuery('node');
    $query->condition('status', NODE_PUBLISHED);
    $entity_ids = $query->execute();
    $nodes = \Drupal\node\Entity\Node::loadMultiple($entity_ids);

    // Loop through all nodes, connecting the webform.
    foreach ($nodes as $node) {
      $form = \Drupal\webform\Entity\Webform::load('MYWEBFORM');

      // Set the value for the hidden field pointing to the 'parent' node.
      $form->setElementProperties('node_reference', [
        '#type'=> 'textfield',
        '#wrapper_attributes' => array(
          'style' => 'display:none',
         ),
        '#webform_id' => 'mywebform--node_reference',
        '#webform_key' => 'node_reference',
        '#value' => $node->get('nid')->value,
      ]);

      // Render form an assign it to each node.
      $rendered_form = \Drupal::entityManager()
        ->getViewBuilder('webform')
        ->view($form);

      $node->form = $rendered_form;
    }
  }

}

```

If I look at the generated markup for each nodes form it see different values in the `node_reference` field, but when I submit the form and then look at the submission all forms have the same `node_reference` value? Can anyone help me figure out what I am doing wrong here or perhaps this could be solved in a much easier way?

It seems like the the value always are set to the `nid` of the first node in the array? Perhaps this is some kind of strange caching issue?

# Answer
I don't know if your problem could be solved in an easier way. A lot of our solutions at my workplace seem equally convoluted. In fact, we use WebformSubmissions to hold a lot of submitted data.

Here is how you set a value in a WebformSubmission:

1. Load the submission.
2. Get the submission's data as an associative array.
3. Change the submission's data however you want.
4. Set the submission's data to this modified array.
5. Save the submission.

Here is the code:

```
use Drupal\webform\Entity\WebformSubmission;

// $sid contains the submission id
$submission = WebformSubmission::load($sid);

$data = $submission->getData();

// you can find the machine name in the devel tab
// or just do what I do and var_dump($data);
$data["field_machine_name"] = "new value";

$submission->setData();
$submission->save();

```
> 3 votes

---
Tags: 8, webforms
---


# Question
Title: Suppress watchdog a specific log message
I would like to tell watchdog **not** to write the "Cron run completed" to the log while leaving all other messages intact. How can I do this?

Thanks!

# Answer
There is no special hook for this. The easiest way to fix this in Drupal 8 is overriding *logger.dblog* service.

According to the official documentation you need implement a class extending *ServiceProviderBase* and the *alter*() method as shown below.

```
<?php

namespace Drupal\example;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the logger.dblog service.
 */
class ExampleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides logger.dblog service to exclude some unwanted log messages.
    $container->getDefinition('logger.dblog')
      ->setClass('Drupal\example\Logger\DbLog');
  }

}

```

The logger itself is extremely simple.

```
<?php

namespace Drupal\example\Logger;

use Drupal\dblog\Logger\DbLog as BaseDbLog;

/**
 * Logs events in the watchdog database table.
 */
class DbLog extends BaseDbLog {

  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = []) {
    if ($message !== 'Cron run completed.') {
      parent::log($level, $message, $context);
    }
  }

}

```
> 9 votes

# Answer
For drupal 7 you could implement `hook_watchdog()` in a custom module to see the error messages but it will not allow you to change the messages logged into database. Read more about `hook_watchdog` here

For deleting specific messages perhaps you could implement `hook_cron` in your own module using something similar to what watchdog does when cleaning itself from excess messages as seen here but you have to adjust the code to find only specific messages to delete.

Perhaps viewing all log message except the ones you mentioned can be done with https://www.drupal.org/project/views\_watchdog which allows you to create a view of dblog message and probably you can use views filtering to filter them out.

Or https://www.drupal.org/project/watchdog\_filtering might be able to do the filtering for you
> 2 votes

# Answer
Instead of trying to **not** write a specific log message, you can also ue the Views Watchdog module (to not include such messages when creating a list of log messages).

Some details about this module (from its project page):

> ... extends the Views module and allows to create customized lists (pages, blocks, feeds) of watchdog entries.
>
> **Features**
>
> This module provides several fields, filter and sort criteria to build custom pages, blocks, and feeds.
>
> It also provides the style Watchdog table to display watchdog entries as highlighted rows in a table.
> 0 votes

---
Tags: log-messages
---


# Question
Title: Content, terms and user/author import or migration to D8 without custom module
How can I only import or simply migrate content (nodes), related terms and users/content-authors from a D7 project into a better structured D8 installation, which is similar to the old project, but meant as a project upgrade replacement, but with changes regarding how things work in D8 and which require to import the data only, apart from the code/modules of the old project?

The D8 installation is already prepared to reflect the old project with the same fields, menus, etc, but it uses different solutions for relationchips than its D7 predecessor. I would love to import content, comments, terms and users seperately (for example as CSV) and with key-ids helping to rebuild their relationchips. But ...

TBH, the migration docs I read over the last days made me even more confused than being helpful since many little in between parts and steps are not further explained so that I can not hook into and alternate the steps for my needs.

All I already know is, that Feeds and Feeds import isn't ready yet and that migrating is rather complex and is made for not only importing content but for whole project structures? But how if so many modules have no D8 version or working upgrade path?

What I read so far is: https://www.drupal.org/docs/8/modules/migrate-source-csv/using-the-migrate-source-csv-plugin

which maybe comes close to what I maybe need for my issue. But I have a hard time to understand parts of it. So I see a use example with

```
 migration_groups:
  - ACME import

```

in it but without explanation if this line is required and what it is about. Googling for migration groups confuse me even more.

Is migrate\_plus with migrate-source-csv the right direction for my purpose and is somebody out there who can help about the terminology of the migration docs and what parts are important to understand?

# Answer
I have successfully migrated D7 content into a D8 site with similar content types using this small drush extension for D8 along with the built-in D8 Upgrade option: https://www.drupal.org/project/migrate\_upgrade

I believe the upgrade process from D7 or D6 is now apart of D8.3+ in the Admin UI and can simply be enabled after drupal 8 installation under the Module listing. Alternatively, you can use Drush via the module above.

Your D8 project just need localhost access to your old site files (such as images,pdfs, etc ... your old Files directory in Drupal 7/6) and database connection access.

It's a rather painless process for simple websites.

Please review the official documentation on performing a drupal 8 upgrade migration
> 2 votes

---
Tags: 8, nodes, users, taxonomy-terms, migrations
---


# Question
Title: Pass a preprocess variable to a template?
In *subtik.theme*, I have:

```
/**
 * Implements template_preprocess_field().
 */
function subtik_preprocess_field(&$variables) {
  if ($variables['field_name'] == 'field_language') {
    $variables['language'] = $variables['element']['#object']->get('field_language')->getString();
    ksm($variables['language']);
  }
}

```

All good. It dumps 'php' to my page, which is correct.

I also have, in *field--node--field-body.html.twig*, I have:

```
...
{{ kint(language) }}
...

```

Not so good. It dumps 'null' to my page. Why not 'php'?

# Answer
At a glance it looks like you have a condition checking for:

`if ($variables['field_name'] == 'field_language') {`

but the template you are using is `field--node--field-body.html.twig` instead of `field--node--field-language.html.twig`.

To get it to pass to field body twig, you would need:

```
  if ($variables['field_name'] == 'field_body') {
    $variables['language'] = $variables['element']['#object']->get('field_language')->getString();
  }

```
> 3 votes

---
Tags: theming, 8
---


title: Strip out MS Word html tags on migrate

text:
# Question
Title: Strip out MS Word html tags on migrate
I've got a migration set up whose source was apparently filled out using MS Word. The JSON source for the migration looks like this in places:

```
{
    "field_courses": "<p class=\"MsoNormal\" style=\"line-height: 14pt; background-position: initial initial; background-repeat: initial initial;\"><u><span style=\"font-size:10.0pt;
font-family:\" new=\"\">Courses Taught (selected)<br />\r\n</span></u>...</p>"
}

```

When the migration completes and I open the resulting node, the field is rendered like this:

The field in question is allowed to use everything from Plain Text all the way to Full HTML. When I save the node manually, not making any changes, all the nonsense is stripped out and I'm left with relatively sane HTML when I check out the source of that field.

I thought maybe it would be as simple as loading the entity by its `pathauto` alias (eg. `/people/[person_id]`) and running `$entity->save()` on it as soon as it's been imported, but that's not removing the formatting. Any way that I can get it to display correctly without requiring a content manager to manually save 500+ nodes?

# Answer
Found a great way to do this automatically after comparing the Devel tab on a node before and after manually saving it. I realize this is a somewhat narrow use case, but I think it's pretty strong nonetheless.

1. Create a CKEditor profile (I called it "Bio Cleaner", machine name `bio_cleaner`) and limit it to the tags and attributes you want. In my case, it's `<a href hreflang> <ul type> <ol start type> <li> <br> <p>`.
2. For any "formatted" text field in your content types, add the new CKEditor profile as an allowed profile.
3. In your migration, rather than just dumping the raw contents into a field name, set it up like so:

(Sorry for the image - Stack Exchange apparently can't format yaml?)

Anyway, the secret sauce is to to set the `/value` key of the target field to the value pulled from the migration, and to set the `/format` key to the new format you created. Drupal will automagically clean up whatever tags aren't included in your profile when it saves the data.

NOTE: this relies on having the Allowed Formats module installed.
> 1 votes

---
Tags: 8, migrations
---


# Question
Title: DrupalGap index.html No connection found on ios simulator
The app is working on web-app, but when I test iPhone" simulator, then have problems with connection:

index.html - No connection found

Failed connection http://app.newwweb.info Check your device's network settings and try again.

I reviewed the changes in settings.js and index.html and are correct.

What can I do?

# Answer
> 0 votes
I met the same problem, but solved it by including the plugin of network-information. Then both ios and android work fine.

`cordova plugin add cordova-plugin-network-information`

---
Tags: javascript
---


# Question
Title: Filter criteria with entity reference field doesn't work
I have a field called event\_author, which is a entity reference to user. These are the settings for the view.

>

They produce the following output.

>

After I add the filter, there is no result anymore. It seems the entity reference is not matching up with *author1*.

>

Why does it happen?

# Answer
I hover over the field. It `says event_author_id`. It should be the id of the author, instead of text. Or If I want to use text 'author1' in filter. I need to add a relationship in the view. Like a mysql join.
> 0 votes

---
Tags: entities, views
---


# Question
Title: How do I fetch the values of an entity's field?
How to query all the values of a particular field. I used `Drupal\Core\Database\Connection object` to fetch the values as below:

```
$connection = \Drupal::database();
$result = $connection->select('node__body', 'n')
  ->fields('n', array('body_value'))
  ->execute()->fetchCol();

```

Is there any Drupal 8 API specifically for this? I need to fetch all values of the field and fetch the field values for a particular node bundle.

# Answer
In Drupal 7, you would use the `EntityFieldQuery` class. In Drupal 8, there is an equivalent service.

```
$query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('changed', REQUEST_TIME, '<')
    ->condition('title', 'cat', 'CONTAINS')
    ->condition('field_tags.entity.name', 'cats');

$nids = $query->execute();

```

In your case, instead of field\_tag.entity.name, you need body.body\_value. See EntityFieldQuery has been rewritten.
If you just need to get all the node IDs, remove all the `condition()` lines, and then use `entity_load_multiple('node', $nids)` to load the full node objects.

In this way, your code is not making assumptions about the tables used to contain the node data. Plus, it can be easily extended to filter the nodes basing on some criteria (node properties, content of fields...).
> 7 votes

# Answer
Although entityQuery is very powerful I believe not everything can and should be done with it. Loading all nodes to get the values might consume to much resources. Using the Database API should be fine with some help of the TableMappingInterface, as stated in the documentation:

> Provides a common interface for mapping field columns to SQL tables.
>
> Warning: using methods provided here should be done only when writing code that is explicitly targeting a SQL-based entity storage. Typically this API is used by SQL storage classes, or other SQL-specific code like the Views integration code for the Entity SQL storage. Another example of legal usage of this API is when needing to write a query that \Drupal::entityQuery() does not support.

```
/** @var \Drupal\Core\Entity\Sql\TableMappingInterface $table_mapping*/
$table_mapping = \Drupal::entityTypeManager()->getStorage('node')->getTableMapping();

$field_table = $table_mapping->getFieldTableName('field_categories');
$field_storage_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('node')['field_categories'];
$field_column = $table_mapping->getFieldColumnName($field_storage_definitions, 'target_id');

$connection = \Drupal::database();
$result = $connection->select($field_table, 'f')
  ->fields('f', array($field_column))
  ->distinct(TRUE)
  ->condition('bundle', 'article')
  ->condition('entity_id', $nids, 'IN')
  ->execute()->fetchCol();

```

*This works so far. But there are still asumptions about the columns `bundle` and `entity_id`. I am not sure if it would be save to assume that they will be allways there. Maybe there are also functions to get the bundle and the entity-id column, but I guess not, because it seems that views makes the same asumptions, see views\_field\_default\_views\_data.*
> 5 votes

---
Tags: nodes, 8, database
---


# Question
Title: Find a node/page in admin by looking at the code
I'm very new to Drupal, and I want to edit some text on the front page. In the **page.tpl.php**, I have this code `print render($page['content'])`, if I remove it, then the area that I want to edit with is disappeared from the front page, so I know this is the right part, but how can I find out which page, content, or node is being called in the backend?

I'm using Drupal 7.55.

# Answer
I'd recommend installing the Devel module and enabling Webprofiler. It gives you a lot of useful meta information about the current request, including the controller and route used:
> 1 votes

---
Tags: nodes
---


# Question
Title: Why do I get this exception when running a query?
> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'default) VALUES ('1', '0', 'LSm', '054', '0')' at line 1: INSERT INTO {prod\_conf\_procuct\_parameter} (prod\_id, price, key1, key2, default) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4); Array ( \[:db\_insert\_placeholder\_0\] =\> 1 \[:db\_insert\_placeholder\_1\] =\> 0 \[:db\_insert\_placeholder\_2\] =\> LSm \[:db\_insert\_placeholder\_3\] =\> 054 \[:db\_insert\_placeholder\_4\] =\> 0 )

```
function _prod_conf_db_query_insert_results_pcpp($arg,$key1,$key2,$price,$default){
watchdog('alert', "Arg: $arg, Key1: $key1, Key2: $key2, Price: $price, Default: $default");
db_insert('prod_conf_procuct_parameter')
  ->fields(array(
    'prod_id'=> $arg,
    'price'=> $price,
    'key1' => $key1,
    'key2' => $key2,
    'default' => $default
    )
  )
  ->execute();
}

```

`watchdog()` gives *Arg: 1, Key1: LGm, Key2: 054, Price: 0, Default: 0*.

The problem is definitively the column "default" because the insert without `default|$default` works.

The column is defined in `hook_schema()` as follows.

```
'default' => array(
          'description' => 'boolean indicates if the new applicated select list has default',
          'type' => 'int',
          'size'=> 'tiny',
          'default' => 0
        ),

```

If I run the following query from PHPMyAdmin, it works.

```
INSERT INTO `prod_conf_procuct_parameter`(`prod_id`, `key1`, `key2`, `price`, `default`) VALUES (1,"LSm","054",0,1)

```

# Answer
> 3 votes
`DEFAULT` is a reserved MySQL keyword. Try:

```
db_insert('prod_conf_procuct_parameter')
  ->fields(array(
    'prod_id'=> $arg,
    'price'=> $price,
    'key1' => $key1,
    'key2' => $key2,
    '`default`' => $default
    )
  )
  ->execute();

```

phpmyadmin does a lot of hand-holding and error squashing for you - it's not advisable to use it as a canonical source of truth for a particular query string's validity.

---
Tags: database
---


# Question
Title: How to trim the Node field is rendered in page.html.twig?
I have rendered the node(custom) field in page.html.twig. Custom field is a summary text field.

And now, I want to trim the text field.

I have tried the below code,

```
{% set summary = node.field_custom|render|striptags %}
{{ summary|length > 10 ? summary|slice(0, 10) ~ '...' : summary }}

```

This is not working in page.html.twig. But its working only in the node.html.twig.

Showing error like,

```
Uncaught PHP Exception Exception: "Object of type Drupal\\Core\\Field\\FieldItemList cannot be printed."

```

How do I trim the summary field which is rendered in page.html.twig.

Please help me to solve this ?

**NOTE: I could not control it in the managed Display section. If the reduce the number in the Trim character section, its not working.**

# Answer
> 1 votes
We had a similar issue on our site recently. You are trying to print a FieldItemList, which has no \__toString function, and therefore cannot be implicitly converted to a string, as you are trying to do.

In your case, `node.field_custom` appears to be a FieldItemList. I know, you thought it was just a string value from a field -- but it's not. Drupal treats ALL fields as FieldItemLists in the API, even in cases where the field can't possibly contain more than one value. (This presumably makes the implementation cleaner.)

---

One quick solution to your problem, although this is a bit messy, is to call `first()`, to get a TypedDataInterface, `getValue()`, which returns an associative array, and `['value']`, in your Twig template, like so:

```
node.field_custom.first().getValue()['value']

```

That should return a string. However, for those functions to be accessible in a Twig template, you need to enable them in `settings.php` and clear the system cache. Here's what worked for us:

```
$settings['twig_sandbox_whitelisted_methods'] = [
        'first',
        '__toString',
        'bundle',
        'id',
        'label',
];

```

But in your case, you may have to whitelist more methods to get what you want.

Here is some more information on discovering variables in Twig templates.

# Answer
> 0 votes
This below code will trim the node field\_custom in page.html.twig. This will also clean the html raw values.

```
{% set summary = node.field_custom.value|render|striptags %}
{{ summary|length > 10 ? summary|slice(0, 10) ~ '...' : summary }}

```

But If the summary text has an image, Alternative text will be shown instead of image.

---
Tags: 8
---


# Question
Title: D7 - Can't set selected value of a webform select element
I'm trying to set the selected value of a webform select form element before it is rendered. I'm using the below code and the textfields are working just fine but no luck with the select options.

```
function mytheme_preprocess_webform_form(&$vars) {
    $vars['form']['submitted']['emailAddress']['#value'] = 'some@email.com'; //This is working
    $vars['form']['submitted']['country']['#selected'] = 'BARBADOS'; // This is not working even though #default value is used instead
}

```

I can't figure it out why this is not working for select field. I would be glad if someone could help me.

Thanks in advance.

# Answer
You can set value by using #value

```
$vars['form']['submitted']['country']['#value'] = 'BARBADOS';

```

But make sure that the select option key should be same

**Example:**

```
<option value="BARBADOS">BARBADOS</option>
$vars['form']['submitted']['country']['#value'] = 'BARBADOS'; //will work

<option value="barbados">BARBADOS</option>
$vars['form']['submitted']['country']['#value'] = 'BARBADOS'; //will not work
$vars['form']['submitted']['country']['#value'] = 'barbados'; //will work

```
> 1 votes

# Answer
For webform forms, I think you have to set #value to TRUE on the option itself.

Something like this should work:

```
$vars['form']['submitted']['country']['BARBADOS']['#value'] = TRUE;

```

If there are any other default values, you'll have to set those to FALSE.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How to add permissions and configure links to a module in the /admin/modules page?
I created a custom module and when I go to `/admin/modules` page it looks like this (no links):

How can I add the configure and permissions links to my custom module, just like Devel does?

# Answer
Configure is the `configure` key in yourmodule.info.yml, containing a route name, usually your primary settings form/page.

Permissions link automatically shows by having permissions defined in your module.
> 4 votes

# Answer
Add this code `configure: yourmodule.settings` in "yourmodule.info.yml" file.

meanwhile create a "yourmodule.routing.yml" file. place the below code in routing.yml file or make changes depends upon your needs.

`yourmodule.settings:
 path: 'admin/config/media/yourmodule'
 defaults:
 _form: 'Drupal\yourmodule\Form\yourmoduleForm'
 _title: 'yourmodule Settings'
 requirements:
 _permission: 'administer site configuration'` you will get the configure link.
> 1 votes

---
Tags: 8
---


# Question
Title: Render node fields in the views-view--[view_machine_name].html.twig
I have a view called customfeedview showing contents of a content type viz. customfeeds. View Setting are given in the picture below:  I created views-view--customfeedview.html.twig to customize the view. Code of the file is given here under.

```
        <div class="box prog">
            <div class="col-md-3"><img src="{{directory}}/images/2000px-Lotus_position.svg.png" ></div>
            <div class="col-md-9">
                    <h3><b>{{ fields.title.content }} </b></h3>
                        <p>{{ fields.body.content }} </p>
            </div>
      </div>

```

But `{{ fields.body.content }}` & `{{ fields.title.content }}` does not render title and body of the contents of type customfeed.

Please help me in this issue as I am totally a beginner in drupal 8. Thank you...

N.B.: Here I am using show-type content instead of fields as only show-type content only give read-more option in the view page. Using show-type fields `{{ fields.body.content }}` is working fine but whenever I changed it to content `{{ fields.body.content }}` is not rendering the values.

# Answer
> 0 votes
You can call the node field in the view template

```
 node.field_(your-field).value

```

This will print the html tags as well, If the node field has the html structure.

```
node.field_(your-field).value | raw (or) node.field_(your-field).value |render|striptags

```

This will clean the html structure and useful to print the node value inside the view.template

NOTE: using node. instead of content. , because content. will be used only the node.html.twig

---
Tags: theming, 8, nodes
---


# Question
Title: Why is it not recommended to change the default language?
I have a fresh installation of Drupal 8.2.5 and want to use it for mostly Spanish content, but keeping the admin interface in English. /admin/config/regional/language says,

> It is not recommended to change the default language on a working site.

And /admin/config/regional/language/detection/selected says,

> Changing the site's default language itself might have other undesired side effects.

What will break if I change the default language? Or is a better question to ask, should I *want* to change the default language? I found this question, but it does not answer my question, aside from also being pre-Drupal8.

Thanks.

# Answer
In Drupal 7 it was total chaos. With Drupal 8 things have improved a lot. It's now possible to switch default language but but there may still be effects:

* URL alias has a language. Changing default language can bring some strange behavior, especially if some alias was created manually: https://www.drupal.org/node/2484411
* Configuration entities can end up not having the right language. You will perhaps need to export the configuration and do some manual work like making sure the exported configuration has the right lang code.
* ...
> 3 votes

# Answer
I got some problems with site settings. For example site name changed to "Drupal" while in initial default language (English) it keep the right site name. Fixing this was a real pain. At the end I exported configuration, changed site name in the yml and re-imported it.
> 0 votes

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


# Question
Title: Empty node workflow state on node after programmatically saving
I have saved a node programmatically, in the following way:

```
  $node_storage = \Drupal::entityManager()->getStorage('node');
  foreach ($entity_ids as $id) {
    $node = $node_storage->load($id);
    if (!$node) {
      continue;
    }
    $node->set('field_tags', $new_tid);
    $node->save();

```

After saving the node I am trying to edit it and I am getting the follow error upon submit.

```
InvalidArgumentException: The state '' does not exist in workflow 'draft' in Drupal\workflows\Entity\Workflow->getState()

```

I believe that this means that my node has no state.

How could I set the node's state?

# Answer
> 1 votes
There's a code for creating a node and indicating its status, maybe it would help:

`<?php
// add node properties
$newNode = (object) NULL;
$newNode->type = '{NODE_TYPE}';
$newNode->title = '{NODE_TITLE}'
$newNode->uid = {USER_ID};
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;`

`// add CCK field data
$newNode->field_{YOUR_CUSTOM_FIELD_1}[0]['value'] = '{DATA_1}';
$newNode->field_{YOUR_CUSTOM_FIELD_2}[0]['value'] = '{DATA_2}';`

`// save node
node_save($newNode);
?>`

---
Tags: nodes, workflows
---


title: Discount on Cart page

text:
# Question
Title: Discount on Cart page
Where in Drupal Commerce does it output the Discount information on the Cart page. I can find the Total Amount but not the Discount. Thanks

# Answer
> 0 votes
Maybe you have to use some additional modules like https://www.drupal.org/project/commerce\_discount and other which are indicated there.

---
Tags: commerce
---


# Question
Title: Ship to multiple addresses on single order
We have below requirement,

We can add multiple products to single order(which is normal).
Our client expect a functionality to ship to multiple address in single order. Which means we should have option to add multiple address in single order and based on client's need, different products should ship to different addresses.

Any one has any experience or idea about the implementation? Or we have to write our custom module for the functionality?

# Answer
This is one of those tasks that take a lot more time on Drupal 7 than Drupal 8, since the Drupal 7 version of Shipping doesn't have native support for multiple shipments.

Your best bet is investigating the Commerce Shipment and Commerce Fulfillment modules, choosing one of them, and then coding the rest.
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: Admin -> Run Updates, Unresolved dependency
When I click **Run Updates** from admin, I got som Unresolved dependency errors. It told me File Entity (Version \>7.x-2.0 required), but I'm using 2.0-beta3, as the next line stated.

**file\_entity.info** is found in `sites/all/modules/file_entity/file_entity.info`

So what am I missing?

# Answer
> 1 votes
> So what am I missing?

Nothing at all, the messages are pretty clear:

The version of CKEditor Media Browser that you're updating to has a dependency on File Entity 7.x-2.0 or greater. You have version 7.x-2.0-beta3, which is not greater than 7.x-2.0, so the upgrade isn't possible.

You need to update File Entity to the required version first, then proceed with the update of the media browser module.

Do bear in mind that the modules you're dealing with are in beta, and haven't had development effort in a while. It's entirely possible that you might not be able to perform the update. Case in point: https://www.drupal.org/node/2838674

# Answer
> 0 votes
The error message could be confusing, since it shows the required version without stripping out the Drupal compatibility part, and the installed version after stripping out the Drupal compatibility part.

The error message you are seeing is produced from this code.

```
    $required_file = $files[$required_module];
    $required_name = $required_file->info['name'];
    $version = str_replace(DRUPAL_CORE_COMPATIBILITY . '-', '', $required_file->info['version']);
    $compatibility = drupal_check_incompatibility($requirement, $version);
    if ($compatibility) {
      $compatibility = rtrim(substr($compatibility, 2), ')');
      $requirements["{<span class="php-variable">$module</span>}-{<span class="php-variable">$required_module</span>}"] = array(
        'title' => $t('Unresolved dependency'),
        'description' => $t('@name requires this module and version. Currently using @required_name version @version', array(
          '@name' => $name,
          '@required_name' => $required_name,
          '@version' => $version,
        )),
        'value' => t('@required_name (Version @compatibility required)', array(
          '@required_name' => $required_name,
          '@compatibility' => $compatibility,
        )),
        'severity' => REQUIREMENT_ERROR,
      );
      continue;
    }

```

As you see, `$version` is set to the value returned from `str_replace(DRUPAL_CORE_COMPATIBILITY . '-', '', $required_file->info['version'])`.

So, the error message is really saying that a version higher than 7.x-2.0 is required, but the installed version is 7.x-2.0-beta3. That is how `version_compare()`, used from `drupal_check_incompatibility()` works, for which the following relation between versions is true.

```
7.x-2.x-dev < 7.x-2.0-alpha12 < 7.x-2.0-beta1 < 7.x-2.0-rc1 < 7.x-2.0

```

This could be confusing, but it makes sense if you think that version 7.x-2.0-beta1 is released (for example) before version 7.x-2.0-rc1, which is released before version 7.x-2.0 (the stable release).

---
Tags: 7
---


# Question
Title: How to link a custom menu to a custom button in drupalgap?
I would like to put the pop-up main\_menu written in the `setting.js` to my custom button. It seems that the path name I use is not correct.

`l('Menu', 'main_menu', { attributes: { 'data-icon': 'star' } })`

I also tried this and does not successful. The second parameter in `l( )` link path is needed.

`l('Menu', { attributes: { 'data-icon': 'star' }, popup: true, popup_delta: 'main_menu' })`

So, what is the correct path name of the main\_menu? or how do I link my custom menu to my custom button or link?

This is how I do my custom popup button:

`var btn_setup = theme('popup', {
 content: theme('jqm_item_list', {
 items: [
 l('View profile', 'user'),
 l('Login', 'user/login'),
 l('Logout', 'user/logout')
 ]
 }),
 button_text: 'Setup',
 button_attributes: {
 'data-icon': 'gear'
 }
 });` It does not popup anthing, even I just put a simple content, such as:

`content:'<p>This is a test</p>'`

nothing happen when clicking the button.

After several experiments, the popup function needs to set the page id.

`var btn_setup = theme('popup', {
 content: theme('jqm_item_list', {
 items: [
 l('View profile', 'user'),
 l('Login', 'user/login'),
 l('Logout', 'user/logout')
 ]
 }),
 attributes: {
 id: drupalgap_get_page_id() + '_this_page_hook'
 },
 button_text: 'Setup',
 button_attributes: {
 'data-icon': 'gear'
 }
 });` So the question is, when I put this button in the header or footer, I want it display in any page. How do I set the page id for any page?

# Answer
When put in the header or footer block, just give the page id the block name. Here is the code:

```
/**
 * Implements hook_block_info().
 */
function footer_intrfc_block_info() {
  var blocks = {};
  blocks['footer_intrfc_block'] = {
    delta: 'footer_intrfc_block',
    module: 'footer_intrfc'
  };
  return blocks;
}

/**
 * Implements hook_block_view().
 */
function footer_intrfc_block_view(delta, region) {

var html = '<div>';
var btn_setup = theme('popup', {
            content: theme('jqm_item_list', {
                items: [
                  l('View profile', 'user'),
                  l('Login', 'user/login'),
                  l('Logout', 'user/logout')
                ]
            }),
            attributes: {
               id: drupalgap_get_page_id() + '_footer_intrfc_block'
            },
            button_text: 'Setup',
            button_attributes: {
              'data-icon': 'gear'
            }
        });
html += btn_setup + '</div>';
return html
}

```
> 1 votes

---
Tags: javascript
---


# Question
Title: Theming custom block in twig file and render variables
I created a custom block and I'm trying to render it in twig file. The file gets used, as I can see its output, but my variable 'my\_variable' defined in the block is not rendered:

in CustomBlock.php

```
public function build() {
    $build = [];

    $build['custom_block'] = [
      '#my_variable' => 'abcdef',
      '#theme' => 'custom_block',
    ];

    return $build;
}

```

in my\_module.module:

```
function my_module_theme() {
  return [
    'custom_block' => [
      'template' => 'custom-block',
    ],

  ];
}

```

in custom-block.twig.html:

```
<div>{{ my_variable }}</div>

```

-\> The twig file gets used and the div is shown, but the variable is empty/is not rendered.

# Answer
You probably just need to define the available variables:

```
function my_module_theme() {
  return [
    'custom_block' => [
      'template' => 'custom-block',
      'variables' => ['my_variable' => ''],
    ],

  ];
}

```

You'll need to rebuild caches for the change to be picked up.
> 3 votes

---
Tags: theming, 8, blocks
---


# Question
Title: Cannot log in to Drupal running alongside WordPress multi-site
I have a Drupal site (7) that I've migrated to a new server. I have a WordPress multi-site install on this server that looks like this at the moment:

* example.com
* store.example.com

I used to have a forum.example.com, but frankly the available WordPress forum options leave a lot to be desired, so I moved my old Drupal forum instead of migrating.

The issue is that I cannot log in to Drupal, from any account, even using a Drush generated link.

I've tried clearing caches, truncating session tables, adding `$base_url` in the settings.php file, setting session.name on both the WordPress and Drupal installations.
I'm at a loss. I've been banging my head against this for 4 hours now. I switched to a secondary domain (forum.example2.com) and it works perfectly; so all I can come up with is that there is some sort of collision between the two frameworks with either the sessions or the cookies.

Why cannot I log in with any account? How can I fix this?

Edit: To be clear, if I change Apache to point a different domain to this installation, everything works fine. I installed Flarum in place of drupal, and am able to log in. This problem is only present when the two frameworks are drupal and WordPress, and they are subdomains of the same main domain

Setting the user manually also doesn't work, for example:

```
global $user;
if(ip_address() == 'my.ip.address'){
   $user = user_load(1);
}

```

If I dump the user object after this it is loaded, but the next page load still leaves my as an anonymous user.

# Answer
> You should disable APDQC module on the old site.

The above was the answer given in comments. If the voting system requires you to choose a winner, I'm not above a simple comment repost answer :D
> 0 votes

# Answer
I bet it was the `COOKIE_DOMAIN` in wp-config.php:

```
define('COOKIE_DOMAIN', 'sub.mydomain.com');

```

Define it without leading dot.
> 0 votes

---
Tags: 7, users, sessions
---


title: Using db_merge if key is ID type serial

text:
# Question
Title: Using db_merge if key is ID type serial
I would like to know if there is any option for db\_merge function to do UPSERT (update or insert) operation in table if key is "id" column of serial type (autoincrementing).

I need to insert new row if "id" is not defined, or update if "id" is specified. For now I have:

```
db_merge('t_project_proposal_writer')
   ->key(array('id' => $state['storage']['project']['proposal_id']))
   ->fields(array( .... ))->execute();

```

where `$state['storage']['project']['proposal_id']` is null, because is not specified and it should create row with next id value. It is not working, returning:

> Numeric value out of range: 7 ERROR: setval: value 0 is out of bounds for sequence "t\_project\_proposal\_writer\_id\_seq"

It is working, when new id is manually specified, but then, how to get last inserted id of table? db\_last\_insert\_id is not working in D7, only in D6.

# Answer
No, there isn't any way to do that now (in or ). Simply put, that's not how Drupal was designed.

Inspect tables created by Drupal. See any increment here? No. It was design decision not to perform any id assignment in database, but leave it all to code. If you go against that decision, you need to implement your own solutions, using more basic `db_select`, `if`, `db_update` and `db_insert`. Or prepare your own query using `db_query`.
> 1 votes

# Answer
This sounds like a good fit for drupal\_write\_record. Something like this:

```
$result = drupal_write_record('t_project_proposal_writer', $fields, !empty($state['storage']['project']['proposal_id']) ? 'id' : NULL);

if ($result === FALSE) {
  // Failure.
}
elseif ($result == SAVED_NEW) {
  // A new record was saved.
}
elseif ($result == SAVED_UPDATED) {
  // A record was updated.
}

```
> 0 votes

---
Tags: database
---


# Question
Title: Drush does not work invoking the local Drush
I have installed new D8 on a remote server using this way https://github.com/drupal-composer/drupal-project . I have pulled files from GitHub and I have run 'composer install' for getting the all vendor files include the local Drush (/vendor/drush/drush/) When I run 'drush status' or 'drush core-status' on the root (or '/web') website directory I have:

```
vagrant@drupalvm8:/var/www/drupalvm/test8$ drush core-status
PHP Warning:  pcntl_exec(): Error has occurred: (errno 8) Exec format error in /usr/local/share/drush/includes/startup.inc on line 412
Warning: pcntl_exec(): Error has occurred: (errno 8) Exec format error in /usr/local/share/drush/includes/startup.inc on line 412
Error has occurred executing the Drush script found at /var/www/drupalvm/test8/vendor/bin/drush.launcher (errno 8) Exec format error

```

# Answer
This Drush issue has been fixed in the recent version (8.1.5 and above) by refactoring how the code was using Phar class.

Here are updated steps how to install Drush using phar (as per `install.md`):

```
# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('http://files.drush.org/drush.phar');" > drush
# Or use our upcoming release: php -r "readfile('http://files.drush.org/drush-unstable.phar');" > drush

# Test your install.
php drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x drush
sudo mv drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init

```

Or by the following one-liner:

```
sudo install <(curl http://files.drush.org/drush.phar) /usr/local/bin/drush

```
> 1 votes

---
Tags: 8, drush, composer
---


# Question
Title: Render simple php function in twig template
I am rebuilding a website in Drupal 8 and the website shows some content with bootstrap classes according to a conditional php function based on time of day

```
function openStatus(){
$open_str = '<span class="badge badge-success">Open<span                   class="hidden-xs"> until 5pm</span></span>';
$closed_str = '<span class="badge badge-danger">Closed<span class="hidden-xs"> - Open Mon-Fri 9AM-5PM</span></span>';
if(gmdate('N') <= 5 && gmdate('H') >= 8 && gmdate('H') <= 16){
echo $open_str;
} else {
echo $closed_str;
}

```

This is what I have so far, which I think works but not sure how to do day of week.

```
{% if "now"|date('H', "Europe/London") >= 8 && "now"|date('H', "Europe/London") <= 16  %}
<span class="badge badge-success">Open<span                     class="hidden-xs"> until 5pm</span></span>
{% else %}
<span class="badge badge-danger">Closed<span class="hidden-xs"> - Open Mon-Fri 9AM-5PM</span></span>
{% endif %}

```

# Answer
Would suggest doing a pre-process function and stuff in the variables everything the template needs to render. The point of Twig is to push the logic back to the PHP side so that your template does not look like "HTML-in-PHP" or "PHP-in-HTML" (whichever way you look at it) as with previous versions of Drupal.
> 1 votes

---
Tags: theming
---


title: Adding custom data to the node object

text:
# Question
Title: Adding custom data to the node object
I have created a content type called providers and when editting said content types users can fill in extra information related to the content.

I have included said form fields using hook\_form\_alter, and the appropriate hook for \_submit applied with it all working fine (saving to db etc)

Where I am stuck is I can access the data, by loading it via hook\_ENTITY\_TYPE\_load call which allows me to access it in \_form\_alter but for some reason when viewing the node, I do not see the data.

Is there a specific way of loading external data on top of node object in d8?

below is how i load the data.

```
    /**
     * Implements hook_ENTITY_TYPE_load($entities)
     */
    function remittance_providers_node_load(array &$entities) {
      //loop thorough the loaded entities
      foreach ($entities as $key => $entity) {
        // if provider node type is being loaded add our data on top of it.
        if ($entity->bundle() == 'providers') {
          $nid = $entity->id();
          $commission_data = currencyStorage::loadCommission(array("companyID"=>$nid));
          if(count($commission_data)>0){
            foreach ($commission_data as $ckey => $comm) {
              $entities[$key]->commission[$ckey]['amount_from'] = $comm->amount_from;
              $entities[$key]->commission[$ckey]['amount_to'] = $comm->amount_to;
              $entities[$key]->commission[$ckey]['commission'] = $comm->commission;
            }
          }
        }
      }
    }

```

I have installed devel and checked all its phases and I dont see it in there.

# Answer
I have found preceding value array with \[x-default\] shows the values. I presume this has to do with the translation module

```
function remittance_providers_node_load(array &$entities) {
  //loop thorough the loaded entities
  foreach ($entities as $key => $entity) {
    // if provider node type is being loaded add our data on top of it.
    if ($entity->bundle() == 'providers') {
      $nid = $entity->id();
      $commission_data = currencyStorage::loadCommission(array("companyID"=>$nid));
      if(count($commission_data)>0){
        foreach ($commission_data as $ckey => $comm) {
          $entities[$key]->commission['x-default'][$ckey]['amount_from'] = $comm->amount_from;
          $entities[$key]->commission['x-default'][$ckey]['amount_to'] = $comm->amount_to;
          $entities[$key]->commission['x-default'][$ckey]['commission'] = $comm->commission;
        }
      }
    }
  }
}

```
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: Feed import of CSV file only in imports the title and nothing else. It also has paragraph fields
I'm trying to import a small subset of my data to test out how well it would go first before importing 20k records. I'm using the latest feeds module with the paragraphs feeds importer (https://www.drupal.org/sandbox/shaney/2862236). For now I'm only importing:

* guid
* title
* field\_client
* field\_award\_status (paragraph field under"award")
* field\_award\_name (paragraph field under "award")

The only successful import is the title, but nothing else shows up. Below is a preview of my csv data and my feed mapping settings. What could I be missing?

# Answer
I checked the csv file in an editor it found the culprit was because I deleted a bunch of records using excel and it left alot of empty commas everywhere. You have to go into the csv file and edit it manually.

Also it wasn't importing because the values need to be in quotes.
> 1 votes

---
Tags: 7, feeds, importing-exporting, paragraphs
---


# Question
Title: How to download a module hosted on GitHub via composer.json?
I've got the following `composer.json` file:

```
{
    "name": "my-project",
    "type": "project",
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        {
            "type": "package",
            "package": {
                "name": "contrib/term-csv-tree-import",
                "version": "dev-master",
                "type":"drupal-module",
                "source": {
                    "url": "https://github.com/grahl/term_csv_tree_import.git",
                    "type": "git",
                    "reference": "master"
                }
            }
        }
    ],
}

```

However after `composer update`, the module is downloaded to the `vendor` folder as:

```
./vendor/contrib/term-csv-tree-import/term_csv_tree_import.info.yml
./vendor/contrib/term-csv-tree-import/term_csv_tree_import.module
./vendor/contrib/term-csv-tree-import/term_csv_tree_import.routing.yml

```

How can I correct above configuration to download the project as a Drupal module under `docroot/modules/contrib` folder? My Drupal root is under `docroot` folder.

# Answer
> 11 votes
You need Composer Installers for that:

```
{
    "name": "my-project",
    "type": "project",
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        {
            "type": "package",
            "package": {
                "name": "contrib/term-csv-tree-import",
                "version": "dev-master",
                "type":"drupal-module",
                "source": {
                    "url": "https://github.com/grahl/term_csv_tree_import.git",
                    "type": "git",
                    "reference": "master"
                }
            }
        }
    ],
    "require": {
        "composer/installers": "^1.2"
    },
    "extra": {
        "installer-paths": {
            "docroot/libraries/{$name}": ["type:drupal-library"],
            "docroot/modules/contrib/{$name}": ["type:drupal-module"],
            "docroot/profiles/contrib/{$name}": ["type:drupal-profile"],
            "docroot/themes/contrib/{$name}": ["type:drupal-theme"]
        }
    }
}

```

---
Tags: composer
---


title: Redirect to a page in a modal

text:
# Question
Title: Redirect to a page in a modal
I have follow this tutorial to make a modal: http://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8

But when the submitModalFormAjax method is called I want redirect the user to a specific page:

```
/**
 * AJAX callback handler that displays any errors or a success message.
 */
public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // If there are any form errors, re-display the form.
  if ($form_state->hasAnyErrors()) {
    $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
  }
  else {
    // <<<--- redirect to homepage
    // $response->addCommand(new OpenModalDialogCommand("Success!", 'The modal form has been submitted.', ['width' => 800]));
  }

  return $response;
}

```

How can I do it?

# Answer
> 1 votes
```
/**
 * AJAX callback handler that displays any errors or a success message.
 */
public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // If there are any form errors, re-display the form.
  if ($form_state->hasAnyErrors()) {
    $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
  }
  else {
    $response->addCommand(new RedirectCommand(Url::fromRoute('<front>')->toString());
    // $response->addCommand(new OpenModalDialogCommand("Success!", 'The modal form has been submitted.', ['width' => 800]));
  }

  return $response;
}

```

---
Tags: 8
---


# Question
Title: Correct way to render fields from query in tpl?
I'm here again to ask for some help, I'm running a query in a custom module to get contents of a node type, with this:

```
$node_type = "mynodetype";
  $nids = db_query("SELECT * FROM {node} WHERE type = :type", array(':type' => $node_type))->fetchCol();
  $nodes = node_load_multiple($nids);

```

And returning $nodes to the template, I'm using a foreach for $nodes array and I get something like this when I print\_r() an element of $nids array.

```
stdClass Object ( [vid] => 12658 [uid] => 1 [title] => Node title [log]
=> [status] => 1 [comment] => 0 [promote] => 0 [sticky] => 0 [nid] =>
12658 [type] => mynodetype [language] => es [created] => 2017
[changed] => 1502159375 [tnid] => 0 [translate] => 0
[revision_timestamp] => 1502159375 [revision_uid] => 1 [mp_idmod]
=> Array ( [und] => Array ( [0] => Array ( [value] => 1 ) ) )
[mp_nmod] => Array ( [und] => Array ( [0] => Array ( [value]
=> Myvalue [format] => [safe_value] => Myvalue ) ) ) [rdf_mapping]
=> Array ( [rdftype] => Array ( [0] => sioc:Item [1] => foaf:Document )
[title] => Array ( [predicates] => Array ( [0] => dc:title ) ) [created]
=> Array ( [predicates] => Array ( [0] => dc:date [1] => dc:created )
[datatype] => xsd:dateTime [callback] => date_iso8601 ) [changed] =>
Array ( [predicates] => Array ( [0] => dc:modified ) [datatype] =>
xsd:dateTime [callback] => date_iso8601 ) [body] => Array ( [predicates]
=> Array ( [0] => content:encoded ) ) [uid] => Array ( [predicates] =>
Array ( [0] => sioc:has_creator ) [type] => rel ) [name] => Array (
[predicates] => Array ( [0] => foaf:name ) ) [comment_count] => Array (
[predicates] => Array ( [0] => sioc:num_replies ) [datatype] =>
xsd:integer ) [last_activity] => Array ( [predicates] => Array ( [0] =>
sioc:last_activity_date ) [datatype] => xsd:dateTime [callback] =>
date_iso8601 ) ) [cid] => 0 [last_comment_timestamp] => 2017
[last_comment_name] => [last_comment_uid] => 1 [comment_count] => 0
[name] => admin [picture] => 0 [data] => b:0; )

```

And inside the foreach, to render the fields I do it this way:

```
<?php print $nid->mp_idmod[LANGUAGE_NONE][0]['value'];  ?>

```

My question is, this is the right way to render the fields value of each node content type loaded? Or I should do it other way?

# Answer
> 0 votes
Personally, I would create an Entity View Mode for the content type with the fields arranged and formatted how I want them, then you can simply do:

```
$node = node_load($nid);
$node_view = node_view($node);
print drupal_render($node_view);

```

In your case, you need multiple nodes, so:

```
$views = node_view_multiple($nids, "name of entity view mode");
print drupal_render($views);

```

Now that you are using an entity view mode, you can give the markup you want in the `node--node_type--view_mode.tpl.php` file, and it will use that.

As for the query and dynamic code, it should go in a preprocess hook, and not the tpl itself. You can return it as a `$variable` to the template being rendered, usually this is a page callback.

Again, I don't know much about your module or where this code is. You could enable Entity View Modes and just shift this code and get rid of it, and leverage Views instead for the same exact result.

---
Tags: 7, theming, nodes
---


title: Is there any Mega menu module?

text:
# Question
Title: Is there any Mega menu module?
I am building a web site using drupal 8 and I want add a mega menu (3 columns menu with images) to the site.

Previously I have used TB Mega menu, but it does not support Drupal 8. Is there any mega menu module that supports Drupal 8, or is there a work-around which allows to install TB Mega menu on Drupal 8?

# Answer
> 1 votes
You can try the Ultimenu module. It has Drupal 8 version too and it's stable.

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

> Ultimenu is the UltimatelyDeadSimple™ megamenu ever with dynamic region creation.
>
> The module manages the toggle of Ultimenu blocks, regions, and a skins library, while leaving the management of block, menu and regions to Drupal.

# Answer
> 0 votes
It Here and it work. https://www.drupal.org/project/we\_megamenu is Drupal 8 Mega menu

---
Tags: theming, navigation
---


# Question
Title: Math Expression in Views: Date functions like now()
Is there Date expressions or function? I'd like to calculate a duration between a date field and today ? Is there a now(), today() function? i'd like this kind of math expression: now() - \[field\_arrival\]

# Answer
If you only want to display the duration between the given date and today in a view then you don't need any calculation.

Just use **time ago** display option and display your given date with this time ago option.

You will have the result something like this -- 1 year 3 months ago.

You can drop text **ago** if you don't need.
> 2 votes

# Answer
Check out time() function. It returns current unix timestamp. Difference of these two fields will give you the difference in seconds which you can convert to minutes/hours/days as needed.

```
$now  = time();
// If $field_arrival is not a Unix timestamp you can use strtotime() to convert it to UNIX timestamp first.
$diff = $now - $field_arrival;

```
> 1 votes

# Answer
Check out the Date Module. It has a sub module called Date Views which gives you what you want: http://drupal.org/project/date.

The generated sql isn't pretty though. If you can use `hook_views_query_alter` instead you really should since you have better control over the result sql.
> 1 votes

# Answer
I managed to do this by setting the output format in my source field to timestamp, via custom date format string: `U` then in the expression field I used:

`time(0) - [field_fieldname]`

Now you can see the offset in seconds from now and the field's timestamp, you can convert that into whatever you need with maths, ie:

Hours:`(time(0) - [field_fieldname]) / ( 60 * 60 )`

Days: `(time(0) - [field_fieldname]) / ( 60 * 60 * 24)`

Etc.

Turns out the ctools module expects maths functions to always take parameters, the correlated php function is `time(void);` so no matter what you put in there it will simply return the current timestamp. Hence the time(0).
> 1 votes

# Answer
my approach

```
$rawtime = \Drupal::database()->query( "SELECT NOW() as currtime " );
$timeObj = $rawtime->fetchAll();

```
> 0 votes

---
Tags: views
---


# Question
Title: How can I change the number of items in a view only for the first page?
I'm trying to build a view with a different number of items for the first page (2 items) than the others (3 items). How can I build it to avoid skipping items ?
I made tests using `hook_views_pre_build()` but the result isn't conclusive as the second page will miss one item (item C):

Here is my current code:

```
function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'my_view' && empty($_GET['page']) {
    //The view normally has 3 items per page, put 2 for the first page.
    $view->items_per_page = 2;
  }
}

```

And here is the result I obtain:

> First page:
>
> * item A
> * item B
>
> Second page:
>
> * item D
> * item E
> * item F

As you can see, `item C` is missing because setting the number of items per page to 3 imply that the first page also has 3 items.

Is there another way to get this working ?

# Answer
This is how I got it working, use two hooks. Assuming we have a view called `my_view` and the display is `page_1`.

Pre-build: Set the items per page to `10` for the first page.

Pre-render: Add an additional CSS class to the view.

```
/**
 * Implements hook_views_pre_build().
 */
function my_module_views_pre_build(ViewExecutable $view) {
  if ($view->id() === 'my_view' && $view->current_display === 'page_1') {
    // Page is zero indexed: first page is NULL or 0.
    if (!$view->getRequest()->query->get('page')) {
      // Default is 9, we set it to 10.
      $view->setItemsPerPage(10);
    }
    else {
      // Set the offset on subsequent pages, because we have one more on the first page.
      $view->setOffset(1);
    }
  }
}

/**
 * Implements hook_views_pre_render().
 */
function my_module_views_pre_render(ViewExecutable $view) {
  if ($view->id() === 'my_view' && $view->current_display === 'page_1' && !$view->getCurrentPage()) {
    // Add CSS class for first page.
    $view->display_handler->setOption(
      'css_class',
      $view->display_handler->getOption('css_class') . ' is-first-page'
    );

    // To attach a library, use:
    // $view->element['#attached']['library'][] = 'my_module/view-first-page';
  }
}

```
> 2 votes

# Answer
Assuming Drupal 7:

What you can do is have two different displays for your view.

This requires the first display to be a 'block' and the second to be a 'page'.

The first display you will change the pager to "Display a specified number of items" and set the number of items to show to 2.

Enable the "more link".

On the second display you change the number of items to 3 and set the offset to 2.

Currently there is no way to have a view's page display have a more link to another display or view.

This only works from a block display to a page display, tho you could have your block display in a panels page.
> 1 votes

# Answer
You could use the offset property to do something like this:

```
function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'my_view') {
    // The view normally has 3 items per page, put 2 for the first page.
    if (!isset($_GET['page']) || $_GET['page'] <= 0) {
      $view->items_per_page = 2;
    }
    else {
      $view->offset = -1;
    }
  }
}

```

Not really the cleanest way to do this since you'll need to change those hardcoded numbers if you change the number of items in the view... But it's fast and it works.
> 0 votes

---
Tags: views, paging
---


# Question
Title: How to limit "drush pm-updatestatus" to check only given project?
When I run the `drush pm-updatestatus drupal` it keeps checking all other projects like:

```
drush pm-updatestatus drupal
Checking available update data ...                                                                                [ok]
Checking available update data for Drupal.                                                                                [ok]
Checking available update data for Views Bulk Operations (views_bulk_operations).                                                   [ok]
Checking available update data for AddThis (addthis).                                                                               [ok]
Checking available update data for Administration views (admin_views).                                                              [ok]
Checking available update data for BeautyTips API (beautytips).                                                                     [ok]
Checking available update data for BUEditor (bueditor).
Checking available update data for Date (date).                                                                                [ok]
Checking available update data for @font-your-face (fontyourface).                                                                  [ok]
Checking available update data for Entity API (entity).                                                                             [ok]
Checking available update data for FAQ Field (faqfield).                                                                            [ok]
Checking available update data for Features (features).                                                                             [ok]
Checking available update data for Feeds (feeds).                                                                                [ok]
Checking available update data for File Entity (file_entity).                                                                       [ok]
Checking available update data for File Field Sources (filefield_sources).                                                          [ok]
Checking available update data for Google reCAPTCHA (google_recaptcha).                                                             [ok]
Checking available update data for Gravatar (gravatar).                                                                             [ok]
Checking available update data for Insert (insert).                                                                                [ok]
Checking available update data for Job Scheduler (job_scheduler).                                                                   [ok]
Checking available update data for jQuery Update (jquery_update).                                                                   [ok]
Checking available update data for Libraries (libraries).                                                                           [ok]
Checking available update data for Mailhandler (mailhandler).                                                                       [ok]
Checking available update data for Mail System (mailsystem).                                                                        [ok]
Checking available update data for Media (media).                                                                                [ok]
Checking available update data for Memcache (memcache).                                                                             [ok]
Checking available update data for Metatag (metatag).                                                                               [ok]
Checking available update data for Mime Mail (mimemail).                                                                            [ok]
Checking available update data for MultiBlock (multiblock).                                                                         [ok]
Checking available update data for OAuth (oauth).                                                                                [ok]
Checking available update data for Extended Path Aliases (path_alias_xt).                                                           [ok]
Checking available update data for Pathauto (pathauto).                                                                             [ok]

```

Is there an alternative to `drush pm-updatestatus` or a way to make it check only the given project?

# Answer
> 0 votes
Since `drush pm-updatestatus` is so noisy, the "Checking available update data" output is IMHO debug output that shouldn't be displayed, I often use `drush pm-releases` (rl) in stead. The drawback with using `drush rl` is that it always produces output - you need to read, and optionally check that "Installed" and "Recommended" is on the same line.

Another work-around is to throw away the debug output:

```
drush pm-updatestatus MODULE 2> /dev/null

```

---
Tags: drush
---


# Question
Title: Create folders in custom installation profile fails when usind drush site-install
I am working on a custom installation profile, and am using `$_SERVER['DOCUMENT_ROOT']` as part of creating custom folders inside `<drupal-root>/sites/sitename.tld/`.
It works as expected when using the UI installation process, but when I try to run it through `drush site-install my_custom_install` it fails. I expect this is because $\_SERVER is never set in the CLI (at least that is what I could understand from search around for a solution).

In terms of the error I get when it fails, it is just a permission denied for creating the folder, since it tries to create it in `/sites/sitename.tld` in the root of the server, which it naturally does not have access to. It's this path that is correctly getting the document root in the UI, but not in CLI.

**Code example that is creating the folder**

```
copyTheme($from, $to, &$context) {
  $site_root = $_SERVER['DOCUMENT_ROOT'];

  $context['message'] = 'Copy theme';

  $source = $site_root . $from;
  $destination = $site_root . $to;

  try {
    // If the destination directory does not exist create it
    if (!is_dir($destination)) {
      if (!mkdir($destination, 0777, TRUE)) {
        // If the destination directory could not be created stop processing
        throw new Error('Could not create custom theme folder \'' . $destination . '\'');
      }
    }

    //if (chmod($destination, 0777)) {
    //  rcopy($source, $destination, $context);
    //}
  } catch (\Exception $e) {
    \Drupal::logger('custom_installer')->error($e->getMessage());
  }
}

```

**Snippet of the actual error output during `drush site-install`**
In the error, `installtester.dev` is the `$project_domain` and `installtester` is the `$project_name`.

```
Error: Could not create custom theme folder '/sites/installtester.dev/themes/custom/installtester' in /var/www/drupalvm/drupal/webroot/profiles/contrib/custom_installer/batch.inc on line 20 #0 /var/www/drupalvm/drupal/webroot/core/includes/batch.inc(252): copyTheme('/themes/contrib...','/sites/installt...', Array)
#1 /var/www/drupalvm/drupal/webroot/core/includes/form.inc(874): batch_process()
#2 /var/www/drupalvm/drupal/webroot/core/includes/install.core.inc(619): batch_process(Object(Drupal\Core\Url), Object(Drupal\Core\Url))
...

```

In case it is relevant, I am doing the development on drupal-vm via vagrant and virtualbox on a windows 10 machine.

**Question**
Is there a better way than using `$_SERVER['DOCUMENT_ROOT']` to get the document root? one that will work both using UI install and `drush site-install`?.

Alternatively, is there a parameter I can check for if I use the `--root` option for `drush site-install`?

# Answer
I found a solution that works.

Drupal sets it's own constants, such as `DRUPAL_ROOT` which can be used instead of `$_SERVER['DOCUMENT_ROOT']`.

So, all I had to do was to change `$site_root = $_SERVER['DOCUMENT_ROOT'];` to `$site_root = DRUPAL_ROOT;`, for it to work correctly when installed via Drush.
> 0 votes

---
Tags: 8, drush, files, installation-profiles
---


# Question
Title: How to remove target id from selected term reference field
While selecting taxonomy from autocomplete term reference field, its target id also get displayed. How to remove target id from display?

In picture displayed, I want only 23456789 not bracket part i.e. (19) from display.

# Answer
> 0 votes
You need alter autocomplete js like this

```
 function theme_name_js_alter(&$javascript,
  \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  $path = \Drupal::service('path.current')->getPath();
  $path_args = explode('/', $path);
   if($path_args[1] == 'twc-partners'){
   //kint($javascript);
     $javascript['core/misc/autocomplete.js']['data'] = drupal_get_path('theme', 'theme_name') . '/js/autocomplete-custom.js';
 }
}

```

This code add in theme file .Please download file from here.

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


# Question
Title: Module(s) doesn't enable properly with Drush
I have installed Acquia's DevDesktop 2 to create local sites and while testing D8.3.6 I have found an interesting issue. When I enable various modules with drush (drush en paragraphs (example)) drush reports the module installed correctly however when I try to use the module the site errors. The way to fix this is to uninstall with drush then use the Drupal UI to enable the module and all is fine.

The version of drush shipped with the latest version of DevDesktop is 8.1.10

Anyone else seen this?

# Answer
> 0 votes
This is a bug in either Drush, Drupal or the Entity Reference Revisions module (which the Paragraphs module depends on). The solution is to enable the Entity Reference Revisions or the Paragraphs module from Drupal itself, not with Drush. You can safely download the modules with Drush.

See my Drush issue at https://github.com/drush-ops/drush/issues/2873 for more information.

No, I can't reproduce this issue with other modules. (I'm using the same setup as you.)

---
Tags: drush, installation
---


# Question
Title: Problems with Search API and Entity Translation
I'm building a two-language website (Ukrainian - main, English - second) with the new Entity Translation approach. This approach seems very promising however it does not support multilingual content indexing.

I planned to use Search API Database Search module for the website. I also installed Search API Entity Translation and Search API Entity Translation Database Search in order to make them play together.

However the behaviour I achieved is the following:

**1. When searching the website from the Ukrainian version**: when searching with Ukrainian keywords the search yields no results; when searching with English keywords the search shows results in Ukrainian (the Ukrainian versions of relevant content in English).

**2. When searching the website from the English version**: when searching with Ukrainian keywords the search yields no results; when searching with English keywords the search shows results in English (with highlighted relevant keywords).

As far as I understand there is a problem with Ukrainian content indexing. Is it somehow possible to fix it?

# Answer
Make sure to enable the "title\_field" field in the Fields tab of the index instead of "title", as well as any other translatable fields you want indexed. Then, make sure to re-index everything.

By default, custom fields aren't enabled there, and neither is "title\_field" which provides translations of titles via the Title module.
> 0 votes

# Answer
**Search API Entity Translation**

Search API Entity Translation module provides multilingual support for the Search API module through integration with Entity Translation.
> 0 votes

---
Tags: 7, search
---


# Question
Title: Add default image to image file programmatically
I am trying to add a default image to an image field in Drupal 8 using the configuration management interface (CMI). Normally once I have a field configured through the admin UI, I would then export the config YAML file for that field so I can add it to my custom module. The issue is that the default image for an image field is content and cannot be directly exported.

If I do export such a file, it would look like this:

```
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_bluescope_header_bg_image
    - node.type.bluescope_page
  module:
    - image
id: node.bluescope_page.field_bluescope_header_bg_image
field_name: field_bluescope_header_bg_image
entity_type: node
bundle: bluescope_page
label: 'Header background image'
description: 'Image used as the page''s header background'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  file_directory: images/header-bg
  file_extensions: 'png gif jpg jpeg'
  max_filesize: ''
  max_resolution: ''
  min_resolution: ''
  alt_field: true
  alt_field_required: true
  title_field: false
  title_field_required: false
  default_image:
    uuid: 8288b3b1-4b0e-4efc-9137-55cb68382f0a
    alt: 'Header background image'
    title: ''
    width: 1920
    height: 1080
  handler: 'default:file'
  handler_settings: {  }
field_type: image

```

I noted that the default image is referred to using a `uuid`. I was thinking that I could address this by programmatically adding the default file to this field's configuration during the module install process. What I tried was to create the image in drupal's file system and then get the `uuid` of that file and add it to the fields configuration using `configFactory`:

```
function colorbond_data_install() {
  $config_factory = \Drupal::configFactory();
  $field_bluescope_header_bg_image_config = $config_factory->getEditable('field.field.node.bluescope_page.field_bluescope_header_bg_image');
  $default_image = $field_bluescope_header_bg_image_config->get('settings.default_image');

  // Create default image file.
  $file_info = colorbond_data_add_file('public://images/header-bg/', 'starwars.jpg', 'Header background image');
  $file = File::load($file_info['target_id']);

  $default_image['uuid'] = $file->uuid();
  $default_image['alt'] = 'Header background image';
  $default_image['title'] = 'Header background image';
  $default_image['height'] = 1080;
  $default_image['width'] = 1920;

  $field_bluescope_header_bg_image_config->set('settings.default_image', $default_image);
  drupal_flush_all_caches();
}

```

The problem is that when I reinstall the module, the default image configuration does not appear:

Not sure what I am doing wrong.

# Answer
Add `->save(TRUE);` as in `$field_bluescope_header_bg_image_config->set('settings.default_image', $default_image)->save(TRUE);`
> 5 votes

# Answer
This is how I do it inside my install profile:

```
function my_profile_install() {

  $config_factory = \Drupal::configFactory();
  $field_my_logo = $config_factory->getEditable('field.field.taxonomy_term.slides.field_my_logo');
  $default_image = $field_my_logo->get('settings.default_image');

  $data = file_get_contents('profiles/my_profile/images/my_logo.png');
  $file_info = file_save_data($data, 'public://my_logo.png', FILE_EXISTS_REPLACE);

  $default_image['uuid'] = $file_info->uuid();
  $default_image['alt'] = 'My logo';
  $default_image['title'] = 'My logo';
  $default_image['height'] = 138;
  $default_image['width'] = 138;

  $field_my_logo->set('settings.default_image', $default_image)->save(TRUE);

}

```

And I export the field and the field storage using the configuration management interface (CMI).
> 3 votes

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


title: 8 - Translate static content

text:
# Question
Title: 8 - Translate static content
In my site there are lot of static content such as section headers and random content. I want to translate them.

Can I translate with them `{% trans %}my content{% endtrans %}` in twig?

If yes, where to insert the translations in the backend?

# Answer
> 2 votes
Yes - you can do it hardcoded in twig, this can be translated via the user interface translation: `/admin/config/regional/translate`. The `locale` module needs to be enabled.

> **BUT**, i would only recommend this method for static content (and maybe random)!

For dynamic content i suggest to use the drupal multilingual feature(s). Start by enabling the module `content_translation`. Then you can edit a node, and add a translation for it in the backend (node/x/edit). See the docs on d.o. for further information.

---
Tags: theming, 8
---


title: How add custom AcessResult reason?

text:
# Question
Title: How add custom AcessResult reason?
When i look at

> AccessResult::forbidden()

We can set a reason as parametter.

So i try this :

```
 public function access(Request $request, AccountInterface $account)
    {

        $userRole=$account->getRoles();

        if(in_array("administrator", $userRole) || in_array("agence", $userRole))
        {
            return AccessResult::allowed();
        }

        return AccessResult::forbidden('TESTTT');
    }

```

If a user try to access my page who call this custom check access, he got :

So it's in french but it's the default forbidden access message. I try to custom this message, and i was thinking about the reason in parameter.

Any idea why i can't get TESTTT as message ?

# Answer
As per function definition:

```
   /**
    * Creates an AccessResultInterface object with isForbidden() === TRUE.
    *
    * @param string|null $reason
    *   (optional) The reason why access is forbidden. Intended for developers,
    *   hence not translatable.
    *
    * @return \Drupal\Core\Access\AccessResultForbidden
    *   isForbidden() will be TRUE.
    */
   public static function forbidden($reason = NULL) {
     assert('is_string($reason) || is_null($reason)');
     return new AccessResultForbidden($reason);
   }

```

So the $reason is only intended for developers.
> 1 votes

---
Tags: 8, users
---


# Question
Title: Updated drush, but status shows old version
I have a D7 site running in a Vagrant VM.

I was getting the following error when attempting to run `drush updb` from the site folder:

> Command updatedb needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
>
> The drush command 'updb' could not be executed.

I simply couldn't figure out why this won't run, so I thought I'd update drush. It was on 8.0.0-rc4.

I updated via composer on my local machine, and when I type `drush --version` it shows 8.1.12.

But, when I run `drush status` it still shows 8.0.0-rc4, and to top it off, I still cannot run `drush updb`

What is going on here?

I have tried running `drush --uri=mysite.local updb` but that doesn't help either.

# Answer
In Vagrant, you need to SSH to the machine and run Drush from there.
> 0 votes

---
Tags: 7, drush
---


# Question
Title: Passing theme suggestions to radio and checkbox children
I have a simple radio button defined by with following YAML:

```
country:
  '#type': radios
  '#title': Country
  '#options':
    1: 'England & Wales'
    2: 'Scotland'
  '#required': true
  '#theme_suggestion': minimal

```

The #theme\_suggestion is my addition, in my .theme file I have the following code:

```
function HOOK_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if (isset($variables['element']['#theme_suggestion'])) {
    $suggestions[] = $hook . '__' . $variables['element']['#theme_suggestion'];
  }
}

```

The combination of these options successfully allows me to override the twig templates for fieldset and radios e.g.:

```
<!-- FILE NAME SUGGESTIONS:
   x fieldset--minimal.html.twig
   * fieldset.html.twig

   x radios--minimal.html.twig
   * radios.html.twig
-->

```

However, these suggestions do not get passed down to the children (form\_element, form\_element\_label and input\__radio), I cannot find any documentation or examples on how to do this.

# Answer
> 1 votes
A possible way is to alter the form in which the radio is used if you know its id, or, for a broader solution, check for each form whether the radio is used. Then you can call this function:

```
    function MY_CUSOMT_FUNCTION(&$form, $theme_suggestion) {
     foreach (Element::children($form) as $child) {
     if (!isset($form[$child]['#theme_suggestion'])) {
       $form[$child]['#theme_suggestion'] = $theme_suggestion;
     }
     MY_CUSOMT_FUNCTION(&$form, $theme_suggestion)
    }
   }

```

You can fine tune it to include only the children of your radio though

---
Tags: 8, forms, theming
---


# Question
Title: Get the position of a paragraphs entity in a nested template
I try to build an accordion or slider element with Paragraphs.

Therefore I create a Slider element which had slides. Unfortunately the first element should always looks different. I can do this with a CSS class, but how to figure out which is the first slide?

Slider:

```
<div class="feature-slider">
    <div class="feature-slider__slides">
        <div class="feature-slider__slides-container">
            {{ content.field_feature_slider_slides }}
        </div>
    </div>
</div>

```

Slide (which will loaded through Drupal Magic):

```
<div class="feature-slide {% if pos == 1 %}feature-slide--active{% endif %}">
  ...
</div>

```

**How can I get/set/access a variable (here pos) with the current position of the loop?**

The Slider uses Paragraphs to add several Slides. The is a template for the slider paragraph--slider.html.twig and paragraph--slide.html.twig for the slides. No For-Loops are involved here. Drupal/Paragraphs rendering the slides through the template with content.field\_feature\_slider\_slides from the slider.

# Answer
For the Slide, are overriding the default field.html.twig template?
If yes, then you can use the Twig Loop variables:
https://twig.symfony.com/doc/2.x/tags/for.html
e.g. loop.first
> 1 votes

---
Tags: theming, 8, paragraphs
---


title: Custom Block Can't Invalid the Cache

text:
# Question
Title: Custom Block Can't Invalid the Cache
I wrote a block in Drupal 8 to render a menu based on the http headers of the request, which contains the users' information from the idp. This menu is supposed to be different from user to user, but currently it is cached once it is generated when the very first user login to the website.

I have tried setting the cache max-age to 0, but it didn't seem to work at all. Then I tried the session of the cache contexts, but still those pages visited by previous users are cached. Neither did header:custid.

Here is a sample code

```
class MyBlock extends BlockBase{
  public function build () {
    return array(
      '#cache'=>array('contexts'=>array('session')),
     '#markup' => ...,
    );
  }

 ...
}

```

Thanks in advance for any help!

# Answer
> 1 votes
> I wrote a block in Drupal 8 to render a menu based on the http headers of the request, which contains the users' information from the idp.

If you want to build a new page for every request then there is no point in using the page cache, so I would uninstall the core module `Internal Page Cache`.

Edit: Just read in drupal planet, BigPipe will be available in Drupal 8.1, then you have a perfect solution for this. But in the meantime running a site without page cache for anonymous users is fine, you still have the dynamic cache and can use the cache tags.

# Answer
> 0 votes
This is because page\_cache module caches complete pages for anonymous users. If you want to have this for them as well and not jsut for logged in users, where dynamic\_page\_cache comes to play, and still keep catching then you have to do it via JS. If this happens just for some anonymous users then you can implement page request/response policy tagged service that will stop page\_cache from serving cached content and instead the dynamic\_page\_cache will be used. See the headers on page request and look for x-drupal-cache and x-dynamic-page-cache headers(they will have hit, miss, uncacheable or they won't be present).

# Answer
> 0 votes
As you can read in this post you should implement the following methods to override the default cache configuration for custom blocks:

* defaultConfiguration()
* getCacheContexts()
* getCacheTags()
* getCacheMaxAge()

In your case, you need to add this code to your block:

```
 /**
  * {@inheritdoc}
  */
  public function getCacheContexts() {
    return ['session'];
  }

```

---
Tags: blocks, 8, caching
---


title: Entity translation not working

text:
# Question
Title: Entity translation not working
I'm using Entity Metadata Wrapper and Entity Translation to programatically add a translation to existing nodes. This is my code, i'ts not working and I'm at loss to understand why:

```
$meta = entity_metadata_wrapper('node', $node);

$new_lang = 'fr';

$meta->language($new_lang);

$meta->language($new_lang)->title = 'Some French Title';

// Other fields are changed, but not shown here

$r = $meta->value();

$handler = entity_translation_get_handler('node',$r);

$translation = array(
  'entity_type' => 'node',
  'nid'         => $node->nid,
  'uid'         => $node->uid,
  'created'     => $node->created,
  'changed'     => $node->changed,
  'translate'   => 1,
  'status'      => 1,
  'language'    => $new_lang,
  'source'      => $node->language,
);

$handler->setTranslation($translation, $r);

$meta->save();

```

# Answer
Most importantly, you should be calling `$handler->saveTranslations();` after setting the translation. Your updated code should look like this:

```
$meta = entity_metadata_wrapper('node', $node);

$new_lang = 'fr';

$meta->language($new_lang);

// The body field is set to be translatable.
$meta->language($new_lang)->body->value = 'Some French Body';

// Other fields are changed, but not shown here

$handler = entity_translation_get_handler('node',$node);
$translations = $handler->getTranslations();

// This is a convenience way to initialize the translation data for
// the new language.
$new_translation = array(
  'language' => $new_lang,
  'source' => $translations->original
) + $translations->data[$translations->original];

$handler->setTranslation($new_translation);
$handler->saveTranslations();
$meta->save();

```

As a last note, the `title` property of a node is not translatable, unless you use the Title module. In that case, you should probably use the `$meta->title_field` accessor to change the value.

Good luck!
> 2 votes

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


# Question
Title: How to put multiple conditions on a field, using Views 3?
I am trying to make **multiple conditions** on a field in Views.

I found Views Conditional that allows only one condition.

I also found Views Custom Conditions, which I still don't really find how to use (very few documentation and the one left is very confusing to me).

So I'd like to find out **How to put multiple conditions on one field, using Views 3**.

# Answer
> 2 votes
Consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

> ... provides a views plugin which modify query to support OR conditions for contextual filters.

A few issues on Drupal.org that may be of some help:

There is also this comment in the support forum.

---
Tags: 7, views
---


# Question
Title: Json-Import of nodes with taxonomy terms
I'm running Drupal 8.3.6 and I try to import a json stream originating from typo3. It is essentially a list of blog posts in this format:

```
[{
    "id": "1",
    "title": "Title",
    "bodytext": "Bodytext with html Mark-Up",
    "datetime": "1269437640",
    "keywords": "term1, term2, term3, term4,..."
},{
    "id": "2",
    "title": "Title 2",
    "bodytext": "Another Bodytext with html Mark-Up",
    "keywords": "term6, term3, term9, term7,..."
}]

```

I came up with a small module following these instructions, which works well for the title and bodytext:

```
protected function createBlog(string $json) {
    $jsonout = json_decode($json, TRUE);

    foreach ($jsonout as $blog) {

      $node = Node::create(array(
        'type' => 'blog',
        'langcode' => 'de',
        'uid' => '1',
        'status' => 1,
        'title' => $blog['title'],
        'body' => ['value' => $blog['bodytext'], 'format' => 'full_html'],
      ));

      $node->save();
    }
  }

```

However I'm struggling to get the terms created and referenced by the nodes. I tried something like this, but it doesn't work:

```
protected function createBlog(string $json) {
    $jsonout = json_decode($json, TRUE);

    foreach ($jsonout as $blog) {
      foreach ($blog['keywords'] as $tag) { // Loop through each blog entries keywords and create terms
        $term = Term::create(array(
          'name' => $tag,
          'vid' => 'tags',
        ))->save();
      }

      $node = Node::create(array(
        'type' => 'blog',
        'langcode' => 'de',
        'uid' => '1',
        'status' => 1,
        'title' => $blog['title'],
        'field_tags' => $blog['keywords'], // I would need to have the terms from above in an array to add them here, right?
        'body' => ['value' => $blog['bodytext'], 'format' => 'full_html'],
      ));

      $node->save();
    }
  }

```

The terms do not get created and if they would, I wouldn't know how to associate them with the nodes. Also if it would work, there would be the problem that on creation of the terms I do not check if a term already exists. This would be necessary because nodes can have the same terms.

Is it possible to achieve this with my approach? If yes, can you tell me how? I also looked in to migrate\_plus but I find it quite complicated.

Any help would be appreciated!

Andi

# Answer
Not knowing how the rest of your dependencies are set up, one thing I notice off the bat is that your `keywords` source field is a comma-separated single string, but you're treating it as an array of values in your processor. Maybe something like this:

```
protected function createBlog(string $json)
{
    $jsonout = json_decode($json, TRUE);

    foreach ($jsonout as $blog) {
        $newTags = explode(', ', $blog['keywords']);
        $newTagIDs = [];
        foreach ($newTags as $tag) {
            $newTagIDs[] = Term::create(array(
                'name' => $tag,
                'vid' => 'tags'
            ))->save();
        }

        $node = Node::create(array(
            'type' => 'blog',
            'langcode' => 'de',
            'uid' => '1',
            'status' => 1,
            'title' => $blog['title'],
            'field_tags' => $newTagIDs,
            'body' => ['value' => $blog['bodytext'], 'format' => 'full_html']
        ));

        $node->save();
    }
}

```

You're right that your approach would create multiple copies of the same term, though. The Entity Lookup plugin from the migrate\_plus module might provide some help:

```
// $this->entityManager is a dependency-injected instance of Drupal\Core\Entity\EntityManagerInterface
$query = $this->entityManager->getStorage('taxonomy_term')
    ->getQuery()
    ->condition('name', $termNameToLookup)
    ->condition('vid', $vocabularyToLookup);
$results = $query->execute();
if (empty($results)) {
    // term doesn't exist in that vocabulary; should add it
} else {
    // the term already exists in that vocabulary; do something with it
}

```
> 1 votes

# Answer
Thanks to mounty for pointing me to the tutorial of Campbell Vertesi to get me started with d8 migrate: https://ohthehugemanatee.org/blog/2017/06/07/stop-waiting-for-feeds-module-how-to-import-remote-feeds-in-drupal-8/

It's a blessing. Also the d8 docs are useful: https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/migrate-process-overview

The crucial part to get my list of tags migrated is this pipeline:

```
field_tags:
    -
      plugin: explode
      source: keywords
      delimiter: ','
    -
      plugin: entity_generate
      lookupBundleKey: vid
      lookupBundle: tags

```

The explode plugin grabs the tags from the list and the entity\_generate plugin checks if the entity exists. If not, the entity is created. The tags are then added to the node. The whole yml file for my import:

```
id: blog_importer
label: 'Blog Importer'
status: true

source:
  plugin: url
  data_fetcher_plugin: http
  urls: 'url/file.json'
  data_parser_plugin: json

  item_selector: blog-entry
  fields:
    -
      name: bid
      label: 'Blog Post ID'
      selector: uid
    -
      name: title
      label: Title
      selector: title
    -
      name: body
      label: Body
      selector: bodytext
    -
      name: keywords
      label: Keywords
      selector: keywords

  ids:
    bid:
      type: integer

destination:
  plugin: 'entity:node'

process:
  title: title
  'body/format':
    plugin: default_value
    default_value: "full_html"
  'body/value': body
  field_tags:
    -
      plugin: explode
      source: keywords
      delimiter: ','
    -
      plugin: entity_generate
      lookupBundleKey: vid
      lookupBundle: tags
  status:
    plugin: default_value
    default_value: 1
  type:
    plugin: default_value
    default_value: toppik_blog

```
> 0 votes

---
Tags: nodes, taxonomy-terms, 8
---


# Question
Title: How to update the language in a existing node entity?
Using `kint($node)` gives me some available methods to use but none seems to be able to set the language of the node.

By guessing, I found `$node->langcode`, which gives me a method `setLangcode($langcode)`, but it does not work.

After loading the `$node->langcode->setLangcode('cat');` and `$node->save();`, the node in the interface does not have the updated language.

# Answer
You should be using the `get()`/`set()` methods (of the FieldableEntityInterface), sth like this:

```
// Get the current node's language.
$node->get('langcode')->value;
// Set the current node's language.
$node->set('langcode', 'de');
// Save the node to persist the change.
$node->save();

```

Hope this answers the question for you.
> 5 votes

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