# Question
Title: Getting literal ampersands from summary field in a view of fields
I have a view where we are using the Body Summary field. I got a bug report that an HTML entity, `&`, displaying, where they wanted a literal ampersand.

When I updated our existing view, based on fields, to use the Body Summary field instead of a trimmed body, I did not find the Body Summary field by itself in the list of fields. So, I added another Body field to the view, and re-wrote its results: `{{ body__summary }}`.

Thinking that the problem was from our site's configuration, I repeated the same steps on a fresh Drupal install: using the Article content type, I added content in the Summary field, and created a view of fields of the Article content type. I got the same behavior on the fresh install.

I posted a question here, but I did not include information about what kind of view I created. I made a mistake from neglect; I did not include all the information needed to understand the situation and answer the question.

A helpful user went through the trouble of creating a fresh install, with two different versions of Core, and reported that he did not get the same behavior, but nonetheless gave a helpful and relevant answer.

That answer got me thinking, and I created a second view of `teaser`s instead of fields. That view has literal ampersands, which is what I want. I concluded that leymanxx, when he did his testing, created a view of teasers, because I neglected to mention what kind of view I made, and thus, he did not see the same behavior that I did.

So now it looks to me that the body field re-write is the origin of the problem. I'm not sure the best way to address it:

1. Did I overlook the summary field in the list of fields somehow? Is there a "right way" to add it, and I simply did it a wrong way?
2. When I inspect the field with the escaped ampersand with theme debugging, it tells me this: `<!-- THEME HOOK: 'views_view_field' -->
<!-- BEGIN OUTPUT from 'core/modules/views/templates/views-view-field.html.twig' -->` When I look at that theme file, apart from the comments, I see only this `{{ output -}}`. Should I override this template? I'm not sure I know how to fix only the HTML escaping issue while ensuring that I'm not creating unwanted side-effects for all my other views. It appears that all views with fields get processed by this template.
3. **Edit** just make a new field, this is too much bother. See edits below.

How do I get a summary field displaying literal ampersand characters in a view of fields in Drupal 8?

**Edit** According to his comments, laymaxx didn't create a view of teasers, but added the body field and set the formatter to "summary or trimmed". We can't use this in our situation, because we never want the trimmed body; first, Drupal does a bad job trimming, and second, our wording in our summary will almost always be different from the first few lines of the body text. We want to use the summary and the summary alone.

At this point, I'm thinking just to add a new field and use that. However, I am curious as to the "right way" to do this, in case I am ever faced with a situation like this in the future.

# Answer
> 1 votes
Override the template and use the twig filter "raw":

1. Add template file to your custom theme. E.g. `/themes/custom/MYTHEME/templates/views-view-field.html.twig`
2. In the above template file add `{{ output|raw }}`
3. Clear cache and refresh

> The raw filter marks the value as being "safe", which means that in an environment with automatic escaping enabled this variable will not be escaped

Source: https://twig.symfony.com/doc/2.x/filters/raw.html

---
Tags: views, theming
---


title: Anchor links to paragraph content

text:
# Question
Title: Anchor links to paragraph content
I have some drupal 8 sites that make heavy use of the Paragraphs and Bootstrap Paragraphs modules.

Some of my users want to be able to create anchor style links to specific paragraph items on pages. For example; a user may wish to link directly to a specific accordion that is halfway down the page. They may wish to do this either from the body of the same page or with an anchor style hyperlink from elsewhere on the site. eg: `mysite.com/mypage#myanchor`

Other than adding a "name" field and creating a specific "anchor link" twig override for every paragraph type and field is there a more straightforward way of doing this?

In messing around with the anchor\_link module It seems it can only find anchors in the body of a node. If you add an anchor to say, the body of an accordion the link function cannot see it.

# Answer
> 3 votes
First you need to set up an ID for the paragraphs. You can do this in oko\_preprocess\_paragraph():

```
/**
 * Implements template_preprocess_paragraph().
 */
function THEME_preprocess_paragraph(&$variables) {
  $variables['paragraph_id'] = $variables['paragraph']->id();
}

```

Now, you can output the ID of the paragraph using `{{ paragraph_id }}` in any paragraph templates you have. So you can copy paragraph.html.twig to your theme, and change this:

```
<div{{ attributes.addClass(classes) }}>

```

To this:

```
<div{{ attributes.addClass(classes) }} id="paragraph-{{ paragraph_id }}">

```

---
Tags: theming, paragraphs
---


# Question
Title: how to rearrange a contents type in view?
I have created a view using 8 content type ,then i choose

page display setting

```
 Display format :Grid full post

Settings :number of columns 2
Alignment : vertical

```

Then view like

```
 Content A           content D
    Content B           Content E
    Content C           content F
                        content G

```

But i want a grid view like

```
 Content A      content E
    Content B      Content F
    Content C      content G
    content D

```

How can i rearrange contents as grid in view?is it possible?please help me?

# Answer
This probably has to do with the content size and CSS that is creating the layout using floats.

You can use other CSS methods for layout that allow for far more control over positioning, but I'm not aware of any ready-made solutions for that. To modify the CSS you need to create a subtheme if you're not already using it, to override the theme with new code, or use a module like CSS Editor.

You can get CSS layout help in other places specialized for that, that isn't a Drupal-related question.
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to get translated field_storage_config
I need to programmatically set the translated values for several fields on a node. For that I would like to set their values in the fields field\_storage\_config. Adapted from another question's answer (Manage config translations programmatically) I tried the following, but without success:

```
$origLang = \Drupal::languageManager()->getConfigOverrideLanguage();
$lang = \Drupal::languageManager()->getLanguage($currentTranslationLanguageId);
$untranslatedStorage = \Drupal::entityTypeManager()->getStorage('field_storage_config')->load("node.$tagsBaseFieldId");
$untranslatedValues = $untranslatedStorage->getSetting('allowed_values');
\Drupal::languageManager()->setConfigOverrideLanguage($lang);
$translatedStorage = \Drupal::entityTypeManager()->getStorage('field_storage_config')->load("node.$tagsBaseFieldId");

```

I expected to get the field\_storage\_config of the override language that I set in the languageManager (different from the base language), but if I dump $untranslatedStorage and $translatedStorage after these commands, they are the same. $untranslatedStorage and $translatedStorage are the same object. How is this possible and how can I programmatically set the translations for my field(s). It is a text list field (the one that translates to a selectbox in the UI).

# Answer
> How is this possible and how can I programmatically set the translations for my field(s)?

You can load language overrides with ConfigurableLanguageManager::getLanguageConfigOverride, set values and save:

```
\Drupal::languageManager()->getLanguageConfigOverride('fr', 'field.storage.node.field_example')
  ->set($key, $value)
  ->save();

```
> 4 votes

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


# Question
Title: Access Individual Fields - Contact Form - Swiftmailer
So I followed the steps here https://drupal.stackexchange.com/a/199464/49661 to configure Drupal 8 to send contact form emails via Swiftmailer.

I created a template in my theme's template directory, `swiftmailer.html.twig`, which the emails do seem to be using. The issue is, I only seem to have access to all the fields at once using `{{ body }}`. This just spits all the field values out in one, giant mess. Random spacing everywhere, random new lines, some fields with labels, some without.

Ideally, I'd like to be able to access individual field values so I can template it. For example:

```
Full Name:
{{ fields.full_name.content }}

```

I've tried kinting a few variables out, but all `body` contains is the cluster of every field value together.

I've also tried creating more variables using `[yourtheme]_swiftmailer_preprocess(&$variables)` after reading very little documenation available here https://www.drupal.org/node/1590184. This doesn't even seem to be ran when a contact form submission is made.

Here's what it looks like when I kint out `body|raw`:

Thanks for any help in advance

# Answer
This definitely isn't a very nice solution, but it does "work".

I created a module, and added this into the `.module` file.

```
function modulename_mail_alter(&$message)
{
  if(empty($message['params']['contact_message'])) {
    return false;
  }

  //$message['body'][1] = str_replace("\n\n\n\n",'',$message['body'][1]);
  //$message['body'][1] = str_replace('   ','',$message['body'][1]);
  $contactMessage = $message['params']['contact_message'];

  // Build message body
  //$message['body'][0] = [];
  $message['body'][1] = [];
  $message['body'][1] = "<br><br>";

  if($contactMessage->hasfield('field_your_name')) {
    $message['body'][1] .= "<br><br>Full Name:<br>";
    $message['body'][1] .= $contactMessage->get('field_your_name')->getString() . "<br><br>";
  }

  if($contactMessage->hasField('field_email_address')) {
    $message['body'][1] .= "Email Address:<br>";
    $message['body'][1] .= $contactMessage->get('field_email_address')->getString() . "<br><br>";
  }

  if($contactMessage->hasField('field_telephone')) {
    $message['body'][1] .= "Telephone:<br>";
    $message['body'][1] .= $contactMessage->get('field_telephone')->getString() . "<br><br>";
  }

  if($contactMessage->hasField('field_mobile')) {
    $message['body'][1] .= "Mobile:<br>";
    $message['body'][1] .= $contactMessage->get('field_mobile')->getString() . "<br><br>";
  }

  if($contactMessage->hasField('field_company')) {
    $message['body'][1] .= "Company:<br>";
    $message['body'][1] .= $contactMessage->get('field_company')->getString() . "<br><br>";
  }

  if($contactMessage->hasField('field_enquiry_type')) {
    $message['body'][1] .= "Enquiry Type:<br>";
    $message['body'][1] .= $contactMessage->get('field_enquiry_type')->getString() . "<br><br>";
  }

  if($contactMessage->hasField('field_version')) {
    $message['body'][1] .= "Version:<br>";
    $message['body'][1] .= $contactMessage->get('field_version')->getString() . "<br><br>";
  }

  if($contactMessage->hasField('message')) {
    $message['body'][1] .= "Message:<br>";
    $message['body'][1] .= $contactMessage->get('message')->getString() . "<br><br>";
  }
}

```

So basically I clear the message, and then build it up again...
> 1 votes

# Answer
Finally found a solution for this problem:

{{ message.params.contact\_message.get('field\_name').getValue().0.value }}

With this you can access any field on your form!

Hope it helps :)
> 0 votes

---
Tags: 8, emails
---


title: Duplicating content blocks

text:
# Question
Title: Duplicating content blocks
Is there a way to clone or make copies of blocks?

For example, we have some blocks that are quite bespoke. We need to make multiple copies of them so we can display certain content within them on different pages.

# Answer
> 1 votes
You can use the entity\_clone module, which allows you to clone entities.

You can also clone blocks

---
Tags: 8, entities, blocks
---


title: Required regions for a theme

text:
# Question
Title: Required regions for a theme
Are there a set of required regions for a theme that they must have?

I thought I read this in the documentation at one point, but I can't find it again.

# Answer
As described in $closure becomes $page\_bottom, new $page\_top and hidden regions, the required regions are:

* content
* help
* page\_top
* page\_bottom
> 7 votes

# Answer
It is not necessary to declare any regions in your custom themes. While it is true that there are a couple of mandatory regions (especially regions\[content\]), drupal provides default regions when these are not declared:

http://drupal.org/node/171205#regions going more in depth on this page http://drupal.org/node/171224

there are some comments discussing the page\_top and page\_bottom region which nicoz mentioned. http://drupal.org/node/171205#comment-5132804
> 1 votes

# Answer
If a theme doesn't define any region, Drupal assumes the theme is using the following regions:

* header
* highlighted
* help
* content
* sidebar\_first
* sidebar\_second
* footer

If by *required* you mean *required to be defined*, then none of the regions must be defined, but in that case Drupal assumes the theme has a set of predefined regions.
If by *required* you mean *required to have*, then that is the *content* region, as reported in Theming Drupal 7 / Writing theme .info files / regions.

> If you override regions in Drupal 7, you are obliged to declare the line `regions[content] = Content`.
> 1 votes

---
Tags: 7
---


# Question
Title: Disable caching on a custom plugin block
I read a lot of posts on how to disable caching on a custom block but none seemed to give the perfect solution.

1. `$build['#cache'] = ['max-age' => 0]` or `public function getCacheMaxAge() { return 0; }`: Do not seem to work, or at least for authenticated users
2. `\Drupal::service('page_cache_kill_switch')->trigger()`: Kill the complete page cache, not only the block ones
3. Lazy builders: Seems to work only for anonymous users

In my case, I have a block which renders a random node and it's clearly an issue while I'm not able to refresh this cache.

So how to set up such a block? (Drupal 8.4.3)

Posts giving not working solutions:

---

Edit:

```
public function build() {
    [...]
    if ($prev_node) {
      $render_controller = \Drupal::entityTypeManager()
        ->getViewBuilder($prev_node->getEntityTypeId());
      $build = $render_controller->view($prev_node, 'pagination');
      $build['#node']->field_custom = 'something';
    }
    return $build;
}

public function getCacheMaxAge() {
    return 0;
}

```

Thank's to @Clive, it seems my issue is not linked to the block cache itself, but to the entity I render in this block. If so, I have no ideas how on to resolve this issue.

**After many searches, D7 `cache_clear_all('field:node:10', 'my_field')` function seems to do what I want to do. What is its equivalent for D8 ?**

# Answer
> 2 votes
Finally found a solution, thanks to MXH on the Drupal Slack. I had to clear the render array cache like this:

```
$render_controller = \Drupal::entityTypeManager()
        ->getViewBuilder($node->getEntityTypeId());
$items['next'] = $render_controller->view($node, 'pagination');
$items['next']['#cache'] = ['disabled' => TRUE];
$items['next']['#node']->my_field = t('some text');

```

# Answer
> 2 votes
I got the same issue that you, here is what it worked for me.

```
/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function MY_MODULE_preprocess_block(&$variables) {
  $blocks_to_cache = [
    'SOME_block',
  ];
  if (in_array($variables['base_plugin_id'], $blocks_to_cache)) {
    $variables['#cache']['max-age'] = 0;
  }

}

```

So, In my my\_module.module I search if I'm displaying this block, then I clean the cache for that block. You can several block names.

# Answer
> 2 votes
Found the solution here - https://stefvanlooveren.me/blog/disable-block-caching-drupal-8

Add the below code to your block code file

public function getCacheMaxAge() { return 0; }

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


title: How do I structure the batch API array?

text:
# Question
Title: How do I structure the batch API array?
I'm working on a Drupal 8 custom module to scrape pages from a site for migration. Since we're dealing with a large number of pages, I wanted to set up batch processing, to deal with timeouts.

I looked at two tutorials, this one, and one here. However, when I ran my batch, it didn't work as expected. The progress bar immediately filled up to all 71 items, and there were no imported pages, but a number of errors in the error log.

To rule out confounding factors, I created a simple module for testing the batch api (I didn't find the batch represented in the D8 examples module). It exhibits the same behavior: it immediately processes all items, and there are no successes, just errors. This an the example error:

```
 Warning: call_user_func_array() expects parameter 1 to be a valid callback, class '\Drupal\batch_test\BatchTestForm' not found in _batch_process() (line 252 of C:\wamp64\www\D8\core\includes\batch.inc)
`#0` C:\wamp64\www\D8\core\includes\bootstrap.inc(566): _drupal_error_handler_real(2, 'call_user_func_...', 'C:\\wamp64\\www\\p...', 252, Array)
`#1` [internal function]: _drupal_error_handler(2, 'call_user_func_...', 'C:\\wamp64\\www\\p...', 252, Array)
`#2` C:\wamp64\www\D8\core\includes\batch.inc(252): call_user_func_array('\\Drupal\\batch_t...', NULL)
`#3` C:\wamp64\www\D8\core\includes\batch.inc(95): _batch_process()
`#4` C:\wamp64\www\D8\core\includes\batch.inc(77): _batch_do()
`#5` C:\wamp64\www\D8\core\modules\system\src\Controller\BatchController.php(55): _batch_page(Object(Symfony\Component\HttpFoundation\Request))
`#6` [internal function]: Drupal\system\Controller\BatchController->batchPage(Object(Symfony\Component\HttpFoundation\Request))
`#7` C:\wamp64\www\D8\core\lib\Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array)
`#8` C:\wamp64\www\D8\core\lib\Drupal\Core\Render\Renderer.php(574): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()

```

The following is the form that I'm using. Both of the tutorials indicate that calling `_batch_process()` is not necessary when calling `batch_set()` in a form submit.

```
namespace Drupal\batch_test\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormBase;

class BatchTestForm extends FormBase {

  public function getFormId() {
    return 'batch_test_admin_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Test Batch'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $batch = array(
      'title' => t('Test Batch'),
      'operations' => [],
      'finished' => 'Drupal\BatchTest\Form\batchCallback',
      'progress_message' => t('Processed @current out of @total.'),
    );

    for ( $i = 0; $i <= mt_rand(10,100); $i++ ) {
      $batch['operations'][] = ['\Drupal\batch_test\BatchTestForm::process',$i];
    }

    batch_set($batch);
  }

  public function process($input, &$context) {
    // log a random string
    \Drupal::logger('batch_test')->notice(base64_encode(random_bytes(10)));
    sleep(mt_rand(1,100));
  }

  public function batchCallback($success, $results, $operations) {
    if ($success) {
      $message = \Drupal::translation()->formatPlural(
        count($results),
        'One page scraped.', '@count pages scraped.'
      );
    }
    else {
      $message = t('Finished with an error.');
    }
    drupal_set_message($message);
  }
}

```

I suspect that something is wrong in the specification of the `$batch` variable, but I've cross-checked it, and it seems to conform to what the tutorials indicate.

The example in the documentation does not clearly indicate how to pass multiple data points to be called on with the same function.

```
  'operations' => array(
    array('my_function_1', array($account->id(), 'story')),
    array('my_function_2', array()),
  ),

```

Interestingly, one tutorial says to pass the data as a single array.

```
$batch = array(
  'title' => t('Deleting Node...'),
  'operations' => array(
    array(
      '\Drupal\batch_example\DeleteNode::deleteNodeExample',
      array($nids)
    ),
  ),
  'finished' => '\Drupal\batch_example\DeleteNode::deleteNodeExampleFinishedCallback',
);

```

Another tutorial indicates to pass each data point as a separate element in the operations array.

```
$operations = [];
foreach ($letters as $letter) {
  $operations[] = ['smackmybatch_process_letter', [$letter]];
}

```

I'm not entirely sure what this one is specifying.

```
  'operations' => array(
    array('disc_migrate', array('courses', array('foo' => 'bar'))),
  ),

```

So, what is the correct way to pass the data that I want to have processed in the batch API?

# Answer
> 2 votes
Thanks for your answers, everyone. First off, I did not name the function properly, as several have noted.

Second, it turns out that the fourth example has the structure that worked for me. I don't know why it would vary, but whatever.

Here's the submit function from my actual, final module:

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $batch = array(
      'title' => t('test batch'),
      'operations' => array(),
      'finished' => 'Drupal\test_batch\Api\Form\batchCallback',
      'progress_message' => t('Scraped @current out of @total urls.'),
    );
    foreach ( \Drupal\test_scrape\Api\Scraper::loadUrls() as $url ) {
      $batch['operations'][] = [
        '\Drupal\test_scrape\Api\Scraper::batchScrape',
        ['test_scrape', [$url]]
      ];
    }
    batch_set($batch);

```

And here's the callback its referencing:

`src/Api/Scraper.php`

```
  /**
   *  wrapper for batch callback
   */
  public static function batchScrape($type, $operations=[], &$context) {
    foreach ( $operations as $url) {
      self::scrape($url);
      $context['message'] = "Migrated $url<br/>\n"  . $context['message'] ;
    }
  }

```

# Answer
> 8 votes
I have a working batch similar to your example. Here is my code with some comments. I see that you don't use a .batch.inc file, maybe there is the problem, just try using it. I will try to use the same class to see if it works for me.

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    //path to file
    $file = drupal_get_path('module', 'diocese_migrate') . '/csv/saint-du-jour.csv';
    //Exploding by ;"0" because the file is malformed
    $lines = explode(';"0"', file_get_contents($file));
    array_pop($lines);

    $operations = [];
    foreach ($lines as $line) {
      $operations[] = ['process_line_saint_du_jour', [$line]];
    }

    $batch = array(
      'title' => t('Migrating Saint of the Day'),
      'operations' => $operations,
      'finished' => 'process_line_saint_du_jour_batch_finished',
      'init_message' => t('Saint of the Day migration is starting.'),
      'progress_message' => t('Processed @current out of @total. Estimated time: @estimate.'),
      'error_message' => t('The migration process has encountered an error.'),
      'file' => drupal_get_path('module', 'diocese_migrate') . '/diocese_migrate.batch.inc',
    );

    batch_set($batch);
  }

```

**diocese\_migrate.batch.inc** file

```
<?php
use Drupal\node\Entity\Node;

function process_line_saint_du_jour($line, &$context) {
  $info = str_getcsv($line, ";", '"');

  $title_fr = 'Saint du jour ' . $info[2];

  $node = Node::create([
    // The node entity bundle.
    'type' => 'saint_du_jour',
    'langcode' => 'fr',
    'created' => REQUEST_TIME,
    'changed' => REQUEST_TIME,
    // The user ID.
    'uid' => 1,
    'title' => $title_fr,
  ]);
  $node->save();

  $context['results'][] = $info[3];
  $context['message'] = t('Migrating Saint du jour @day', array('@day' => $info[3]));
}

function process_line_saint_du_jour_batch_finished($success, $results, $operations) {
  // The 'success' parameter means no fatal PHP errors were detected. All
  // other error management should be handled using 'results'.
  if ($success) {
    $message = \Drupal::translation()->formatPlural(
      count($results),
      'One Saint of the Day processed.', '@count Saint of the Day processed.'
    );
  }
  else {
    $message = t('Finished with an error.');
  }
  drupal_set_message($message);
  //$_SESSION['disc_migrate_batch_results'] = $results;
}

```

# Answer
> 3 votes
**Some points about the code you provided:**

1. The method (or methods) defined in the `'operations'` list should be correctly namespaced; you are using the wrong namespace, which is why see that warning comes and the whole batch is failing.
2. The method (or methods) defined in the `'operations'` list should be part of a separate class, as a best practice.
3. The method (or methods) defined in the `'operations'` list should be defined as `public static` methods, as the batch API should not be expected to construct objects, and it should be able to access the method.

**General answer to your question:**

The correct way to pass data to the batch processing function, is by enclosing them in an array; this is the normalized format that allows you to pass multiple arguments to your function. For example, and for the following batch processing function:

```
namespace Drupal\mymodule;

class MyBatchClass {
  ...
  public static function myBatchProcessorCallback(
    $someString,
    $uid = 1,
    &$context) {
    ...
  }
}

```

you can add the following operations to your batch definition array:

```
$batch = array(
  'title' => $this->t('Dummy processing'),
  'operations' => [
    [
      '\Drupal\mymodule\MyBatchClass::myBatchProcessorCallback',
      ['randomStringA'],
    ],
    [
      '\Drupal\mymodule\MyBatchClass::myBatchProcessorCallback',
      ['randomStringB', 2],
    ],
  ],
);

```

Hope this helps, it really does seem that the namespacing is causing all your worries, good luck.

# Answer
> 3 votes
As this was for me a really time consuming issue, I uploaded an example module on my GitHub page: drupal 8 batch import example with interaction.

```
$batch = [
  'title' => t('Importing animals'),
  'operations' => [],
  'init_message' => t('Import process is starting.'),
  'progress_message' => t('Processed @current out of @total. Estimated time: @estimate.'),
  'error_message' => t('The process has encountered an error.'),
];

foreach($data as $item) {
  $batch['operations'][] = [['\Drupal\batch_import_example\Form\ImportForm', 'importAnimal'], [$item]];
}

batch_set($batch);

```

---
Tags: 8, batch-operations
---


# Question
Title: How to Make Managed File Field Available to Twig Template?
I am wanting to make it so that users can upload images to a block configuration form for a pre-existing (views-generated) block (views\_exposed\_form) and have the images available in the block's template file. Here's my block class:

```
<?php

namespace Drupal\exposed_filter_images\Plugin\Block;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\Block\ViewsExposedFilterBlock;

/**
 * Provides a 'Views Exposed Filter' block.
 *
 * @Block(
 *   id = "exposed_filter_images_block",
 *   admin_label = @Translation("Exposed Filter Images Block"),
 *   deriver = "Drupal\exposed_filter_images\Plugin\Derivative\ExposedFilterImagesBlock"
 * )
 */
class ExposedFilterImagesBlock extends ViewsExposedFilterBlock {

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

    $form['image_1'] = [
      '#type' => 'managed_file',
      '#upload_location' => 'public://images/steps/',
      '#title' => t('Image 1'),
      '#description' => t("Image on the left"),
      '#default_value' => $this->configuration['image_1'],
      '#upload_validators' => [
        'file_validate_extensions' => ['gif png jpg jpeg'],
        'file_validate_size' => [25600000],
      ],
      '#states' => [
        'visible' => [
          ':input[name="image_type"]' => ['value' => t('Upload New Image(s)')],
        ]
      ]
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['image_1'] = $form_state->getValue('image_1');
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $output = parent::build();

    $output['#theme'] = 'views_exposed_form';
    $output['#files'][0] = $this->configuration['image_1'];

    return $output;
  }
}

```

Here's my `exposed_filter_images.module` file:

```
<?php

/**
 * Implements hook_theme().
 */
function exposed_filter_images_theme($existing, $type, $theme, $path) {
  return [
      'views_exposed_form' => [
          'variables' => ['files' => []],
      ],
  ];
}

/**
 * Implements hook_block_alter().
 */
function exposed_filter_images_block_alter(&$plugins) {
  if (isset($plugins['views_exposed_filter_block:elder_index-page_1'])) {
    $plugins['views_exposed_filter_block:elder_index-page_1']['class'] = \Drupal\exposed_filter_images\Plugin\Block\ExposedFilterImagesBlock::class;
  }
}

```

And then in the `views-exposed-form.html.twig` file, I can have a number returned with this simple debug: `{{ files.0|json_encode }}` (without the |json\_encode filter, nothing shows up), but I'm not really understanding what this number is is or what I can do with it.

So I'm looking for what I would need to do in the class or in the twig file in order to have an image or at least the URL to the image appear on the front-end.

Thanks in advance!

# Answer
Since my rep isn't high enough to comment... yet, I have to add my comment as an answer.

My initial thought is that the file would be saved as an entity. After reading up a bit on some d.o comments, there is/was a bug where managed\_files are temporary by default. Somewhere in the mix you'll need to add something similar to

```
   $image = $form_state->getValue('image');
   $file = \Drupal\file\Entity\File::load( $image[0] );
   $file->setPermanent();
   $file->save();

```

to make the file permanent. (credit to This question)

Most likely you will need to save the file itself as an entity in the `blockSubmit` function.

```
    $file = \Drupal\file\Entity\File::load($image_id[0]);
    // Change status to permanent.
    if(gettype($file) == 'object'){
      $file->setPermanent();
      // Save.
      $file->save();
      $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
      $file->setOwner($user);
    } ... and so on.

```

After that, you should be able to pass the filename or file entity to your theme layer and load it in your preferred method.

Examples modified from This d.o post
> 1 votes

---
Tags: views, 8, blocks
---


# Question
Title: Paragraph type can't delete individual items
I use Paragraph module `Version: 8.x-1.5`. Somehow I can't delete individual items anymore?

Is there a settings somewhere I missed?

# Answer
I have this same problem and also have a link field set to unlimited. I don't see a remove button. Evidently there is a patch in progress for this specific issue. https://www.drupal.org/project/drupal/issues/1038316
> 0 votes

---
Tags: 8, paragraphs
---


# Question
Title: Custom module files written in Windows aren't being recognized when migrated to Linux
I've developed several custom modules in my development environment. My current development environment is Drupal 8 in XAMPP running under Windows and I write the code in Netbeans. I'm getting close to production and I wanted to setup a development environment that mirrors production, so I setup Drupal in CentOS running in VirtualBox.

The problem is, is when I copied over my custom modules Drupal won't recognize them. They don't show up at all under Extend in the list of modules to install. I'm able to open and view the files in VIM and they don't look corrupted in any way. Also, If I create a module natively in CentOS it is recognized just fine. I'm reasonably confident permissions aren't the issue, I've tried setting everything to 777. I'm not 100% sure being written in Windows is the root cause however all the evidence points that way.

Is this a common problem? If so, what can I do to make Drupal recognize these files?

Thanks!

# Answer
> 0 votes
I believe I've figured it out. This issue may not be consider specific to Drupal but Drupal does seem to be a little more particular about files copied over from a Windows dev site.

To get the files to work I had to do two things and in this order:

1. Recursively convert all files in "/path" from Windows format to Linux format.

> find /path -type f -print0 | xargs -0 dos2unix
2. Even after doing step #1 Drupal didn't like the files. I ran this to build a new directories.

> rsync -r /input-path /output-path

---
Tags: 8
---


# Question
Title: Render image field with custom image style in custom block template
This is basically the same question as this, but I can't get the technique to work in a custom block type template: https://drupal.stackexchange.com/a/219052/71100

1. I have a custom block type called `link_card`.
2. I have an image field `field_link_card_image`.
3. I have a List(text) field to select an image style `field_link_card_size`
4. I have confirmed that `field_link_card_size` is outputting the key, which is the machine name of my image style.
5. My theme template is `block--bundle-link-card.html.twig`. It overrides `block.html.twig`. The template is working.
6. I want to render the image and use the image size selected.

Here is the **first** way I tried based on what worked in the answer for `page.html.twig`.

```
{% set image = {
  '#theme':      'image_style',
  '#style_name': content.field_link_card_image_size[0],
  '#uri':        file_url(content.field_link_card_image['#items'].entity.uri.value),
  '#alt':        content.field_link_card_image[0].alt,
 } %}

 {{ image }}

```

I get this white screen error:

> Error: Call to a member function transformDimensions() on null in template\_preprocess\_image\_style() (line 303 of core/modules/image/image.module).

And this error in Report Log in the admin area:

> Warning: array\_flip(): Can only flip STRING and INTEGER values!

If I replace the value for `'#style_name:` with the just the machine name of one of my image styles (such as `square`) it *almost kinda* works.

* The image renders but with the \_incorrect image src: `/D8_1318_LinkCard/web/files/styles/square/public//D8_1318_LinkCard/web/files/2019-06/unsplash_1500x500-4.jpg?itok=c16MdkOY` (You can see it's sort of repeated itself.)
* The alt text doesn't come in at all, so I probably have that wrong, too.

This leads me to believe that **there are problems how I'm pulling in the field content from the block.**

Here is the second way I tried:

```
{% set image = content.field_link_card_image[0] %}
{% set imagestyle = content.field_link_card_image_size[0] %}|
{% set image = setimage|merge({ '#image_style': imagestyle }) %}

{{ image }}

```

The errors are:

> Error: Call to a member function transformDimensions() on null in template\_preprocess\_image\_style() (line 303 of core/modules/image/image.module).
>
> and
>
> Warning: array\_flip(): Can only flip STRING and INTEGER values!
>
> and
>
> Error: Call to a member function transformDimensions() on null in template\_preprocess\_image\_style()

This works if I do `imagestyle = 'square'`. But of course I'm trying to use the value of the field.

Here the problem seems to be an issue with getting in the field\_image size to sneak into the variable `imagestyle`.

**TLDR:** How do I render an image field with a custom style in the *custom block template*.

Thanks!

# Answer
This module is exactly what I need. https://www.drupal.org/project/field\_image\_style

:D
> 0 votes

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


# Question
Title: Default sort order on the other table columns
I render a table with `theme_table()` and use tablesorting (sql) for that. It all works fine.

Except for the intial/default sort on the other tables. No user sort option defined yet. Example:

```
Name | Age ▼

```

Sort by "age" is defined in the `$header`. User clicks on "Name". That now gets sorted **ascending**. Regardless! I need **descending**.

Click:

```
Name ▲ | Age

```

But I need/want:

Click:

```
Name ▼ | Age

```

Studying the code that determines the default sort order, in tablesort\_header, I come across the following:

```
else {
  // If the user clicks a different header, we want to sort ascending initially.
  $ts['sort'] = 'asc';
  $image = '';
}

```

I see no way to avoid this. Do you? Did I miss some parameter, option? I refuse to believe that Drupal makes such a silly assumption without letting developers override it.

# Answer
No, it isn't possible at this point.

There is an issue for that, I suggest you try that out and report back so that it can be commited soon: http://drupal.org/node/109493
> 3 votes

# Answer
You can override it, but probably not the way you would like. `tablesort_header` is called from within `theme_table`. I guess the reason why it have been hardcoded like this, is that is's a utility function for a theme function.

You can override `theme_table` and change the behavior, though I must admit it would have been nicer to have it been determined by a variable.
> 2 votes

# Answer
There is a work around, if you are able to define the link that takes you to the page with the table you want sorted.

Simply craft the link to be the same as if you had clicked on the column to make it descending. The link will have the table column name and sorting defined as fragments: www.domain.com/table\_page?order=title&sort=desc

At least this is not a core hack, and it will persist over pagination links.
> 0 votes

# Answer
Here's how I did it with a custom module using #attached and a **.js behavior**:

**example.js**

```
(function ($) {
  Drupal.behaviors.myFoo = {
    attach: function (context, settings) {

      var th = document.querySelectorAll('#my-container table.sticky-table thead th');
      if (th) {
        for (var i = 0; i < th.length; i++) {
          var el = th[i];
          if (el.classList.contains('active')) { continue; } // Skip the active column.
          var a = el.querySelector('a');
          a.setAttribute('href', a.getAttribute('href').replace('sort=asc', 'sort=desc'));
        }
      }

    }
  };
}(jQuery));

```

It simply iterates over each column in the table (skipping the active column), the replaces the `sort=asc` with `sort=desc` on each link.

Quick and dirty, that's what she said.
> 0 votes

---
Tags: theming
---


# Question
Title: where to put addCommand when implement ajax callback commands
i' m trying to load a dynamic value on every node of my site and i want to achieve this via ajax callback commands and writing custom module so i have a class in src/ajax folder of module like:

```
class TestCommand implements CommandInterface
{
..
  public function render() {
    return array(
      'command' => 'test',
      'text' => $this->message,
    );
  }
}

```

also a js file:

```
(function($, Drupal) {
  alert('loaded');
  /**
   * Add new command for reading a message.
   */
  Drupal.AjaxCommands.prototype.test = function(ajax, response, status){
    alert('called');
    console.log(response);
  }
})(jQuery, Drupal);

```

but i don't know where i am supposed to put this below lines to call command on every node/view. if i put this in `mytheme_preprocess_node` -checking with var\_dump()- i can see
correct response but it doesn't call `Drupal.AjaxCommands.prototype.test`

```
  //where to put this lines to call test command on every node view.
  $response = new AjaxResponse();
  $response->addCommand( new TestCommand('someparam'));
  return $response;

```

js file is loaded because i get 'loaded alert'.

lots of examples on sites, call this via ajax callback in form. one have different approach but i don't know how to apply these solutions in my situation.

# Answer
> 2 votes
You put it in a controller like shown in the linked question, not the answers. Then this topic might be helpful how to trigger the ajax controller: How to Trigger Existing, Non-Form Ajax from JavaScript Event

For passing the node ID to the controller use a route parameter:

```
myModule.myRoute:
  path: '/myajax/node/{node_id}'
  defaults:
    _controller: '\Drupal\myModule\MyController::getNode'
    _title: 'Node'
  requirements:
    _permission: 'access content'

```

Now you can add the node ID to the endpoint url

```
var url = '/myajax/node/' + node_id;
Drupal.ajax({url: url}).execute();

```

and received it by the controller:

```
public function getNode($node_id) {

```

---
Tags: 8, ajax
---


title: Multiple or Single Git Repository

text:
# Question
Title: Multiple or Single Git Repository
Though this isn't about a Drupal issue specifically, it is specific to Drupal. I'm looking for community opinion on best practices for storing multiple versions of Drupal. In my case, I've got a production D7 site. And, I'm developing a Drupal 8 site.

I have pretty strong reasons for keeping those repositories separate. However, I've gotten pushback from management questioning why we can't just have one repository with a production branch for d7 and one for d8.

# Answer
> 2 votes
multiple repos is best option, I recommend even custom modules or themes (for Drupal 8) have individual repos that way you can better manage these and re-use them in other projects more efficiently. assuming your using composer for package management.

---
Tags: 8
---


title: How to come up with SELECT queries?

text:
# Question
Title: How to come up with SELECT queries?
I have a query like this:

```
SELECT DISTINCT field_name FROM table_name

```

I tried:

```
\Drupal::database()->select('table_name', 't');
$query->fields('t', ['field_name']);
$result = $query->execute();

```

But since `Connection::select` expects base table this did not work.

How am I supposed to execute it? I used entityQuery previously. I could not find a way to filter out the unique values of only one field using entityQuery.

**Note**: I went through this example which is basically using `Connection::select`. But `Connection::select` requires to provide the base table. In entityQuery (https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3AentityQuery/8.2.x) I did not have to provide the base table data.

# Answer
> 3 votes
The Problem is, that you need to fetch the results from your execution.

Your code should look like this:

```
$query = \Drupal::database()->select('table_name', 't');
$query->fields('t', ['field_name']);
$query->distinct();
$result = $query->execute()->fetchAll();

```

That does the same as the query you stated above. Alternatively you can fetch your results with a complete custom query:

```
$result = Drupal::database()->query('SELECT DISTINCT field_name FROM table_name')->fetchAll();

```

Notice here that you dont have to `execute()` your query in this case. Instead you can directly fetch your results. You will still need the `execute()` for insert/update or similiar queries.

---
Tags: 8, database
---


title: Git merge issues with Composer.lock

text:
# Question
Title: Git merge issues with Composer.lock
We have a simple setup.

We update our drupal 8 sites on a local machine using `composer update`

we commit the lock file and json file and push to a gitlab git repo

We then pull to a staging server where we run `composer install --no-dev`

This has worked great until now, however, we have run in to an issue I do not understand. On one specific site, no others, the git pull ALWAYS triggers a confict on the lock and json files. No new changes are applied and instead we get a mess of merge conflicts in the lock file.

I do not want to run the update on the staging server. I just want to pull my version controlled lock and json files and install. Is I try to reset --HARD on the merge I end up breaking the entire site and have to revert to a backup...

What would cause this issue? Why is my `composer.lock` file specifically continuing to get merge conflicts? I never run update on the remote server.

What steps can I take to identify the cause?

# Answer
Sounds like some one has changed the `composer.lock` on the staging server. Each time you resolve a merge conflict a new commit is made. In case you don't push the new commit, each time you run `git pull` a new conflict will be caused.

A step to see what causes the first merge conflict would be `git diff composer.lock`.
> 2 votes

---
Tags: 8, composer
---


# Question
Title: How to change the value of the Submit button text when extending ConfigFormBase
I need to change the value of the Submit button text when extending ConfigFormBase. What is the correct way to do it?

# Answer
The submit button is defined in the base class and you can change it:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['actions']['submit']['#value'] = $this->t('Save my configuration');
    ...

```
> 5 votes

---
Tags: 8, forms
---


# Question
Title: How do I filter on day & month from a date field?
Hello I'm still fairly new to drupal and views,

I'm trying to create a Birthday notifier which checks "today" in a view block. Now users can turn in their birthdays on their profile using the date field which is set as: yyyy/mm/dd.

Now the simple thing was to create a filter on the date today, but because of the yyyy field it wil not show up on today's date.

What I'd like is to filter mm/dd on today. So for example if someone's birthdate is 1993/07/03, he'd be notified as today is this persons birthday.

Is there a way to do this or to create a work around for this?

# Answer
> 0 votes
Maybe you could conjure up something with the Regular expression inside the Date Filter, but that is usually not a nice path.

I haven't tried it but maybe you can do it with Contextual Filters (Under Advanced settings in the third column in Views). There is a separate Contextual filter for month, and for day:

`node.field_date (month)` and `node.field_date (day)`

Configure them with Default values `Current date`.

---
Tags: 8
---


# Question
Title: How to add db_select condition by using two concatenated fields?
So I have users with a `field_first_name` and a `field_last_name` and I need my query condition to be something like:

```
"field_first_name + ' ' + field_last_name LIKE :q".

```

Currently I have:

```
->condition(db_or()->condition('fn.field_first_name_value', $q, 'like')->condition('ln.field_last_name_value', $q, 'like'))

```

so if first name is "John" and last name is "Smith" and I search for "John S" I get nothing because it doesnt match the first OR last name, I need to check if it matches the firstname + the last name.

How do I do this in Drupal 7?

# Answer
You can try something like the following. You build the name with a small sql expression and then can use it within the where clause.

```
$select = db_select('people_table', 'p');
$select->addField('id');
$select->addExpression("CONCAT(p.first_name, ' ', p.last_name)", 'full_name');
$select->condition('p.full_name', $some_name, 'LIKE');
$results = $select->execute();

```
> 9 votes

# Answer
The approach added by @travis works, but the others do not.

Here's an example of how you could query for a first name and last name with wildcard string matching. In my case, I'm using the redhen\_contact table.

```
$name = 'Andy G';
$select = db_select('redhen_contact', 'rc');
$select->fields('rc');
$select->range(0, 10);
$select->where("CONCAT(rc.first_name, ' ', rc.last_name) LIKE :q", array(':q'=> '%' . $name . '%'));
$results = $select->execute();

```
> 1 votes

# Answer
In my case, I have separates field for first and last name. I use `addExpression` with `havingCondition`:

```
$query->fields('u', array('uid'));
$query->addExpression("CONCAT(ln.field_last_name_value, ' ', fn.field_first_name_value)", 'full_name');
$query->join('field_data_field_first_name', 'fn', 'u.uid = fn.entity_id');
$query->join('field_data_field_last_name', 'ln', 'u.uid = ln.entity_id');
$query->havingCondition('full_name', '%' . $keyword . '%', 'LIKE');
$uids = $query->execute()->fetchCol();

```
> 0 votes

---
Tags: 7, database
---


# Question
Title: Render form element of type text_format, keeping WYSYWIG format
In Drupal 8 I have a form element fo type `text_format`, and I need to render it in a twig, but keeping the same format was entered in the WYSYWIG editor. I need to know how to render this element form, keeping the format? this its done in a custom form.

```
$form['template'] = [
  '#type' => 'text_format',
  '#title' => 'My title',
  '#rows' => 100,
  '#cols' => 120,
  '#format' => 'full_html',
];

```

# Answer
The solution is render it using the `#type => processed_text`. That's it, then you will see the element renderd keeping the format used in WYSYWIG.

```
$elements = [
  '#type' => 'processed_text',
  '#text' => $data,
  '#format' => 'full_html',
  '#langcode' => 'en',
];

```
> 1 votes

---
Tags: theming
---


# Question
Title: Configure a view to display nodes that match a term value of the container node
I have two content types:

* Programs
* Events

I have a vocabulary:

* Programs

I have a view that displays Events, and I place the view in my Programs nodes.

Both Programs and Events have a field\_term\_programs that references the Programs vocabulary. If I place the view in a Programs node, I want it to display any Events assigned to the same Programs term as that Programs node. I have tried to set this up using contextual filters but have had no luck thus far. The views block is displayed in the Programs node, but no nodes are displayed within the block.

# Answer
The request to show sibling nodes through Taxonomy is one of the most common Views requests.

You case seems to be the simplest one, you can use the `Has taxonomy term ID` Contextual filter.

1. Create your Views listing Events
2. Add the `Has taxonomy term ID` Contextual filter and configure it:

`When the filter value is NOT available`
**Provide default value**
**Taxonomy term ID from URL**
**Load default filter from node page, that's good for related taxonomy blocks**
**Filter to items that share any term**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Taxonomy term ID**
**\[your vocabulary\]**
**Single ID**
3. Place your Block Display on Programs nodes and configure Block settings for the contextual filter.
> 1 votes

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


# Question
Title: Get site name config value in page.html.twig template
Is there a way to get the site name config value as a variable in the page.html.twig template? I am only able to get null values when I try to get the value in the preprocess function.

# Answer
> I am only able to get null values when I try to get the value in the preprocess function.

Null values based on doing what exactly?

The site name, logo etc. was moved to a block, that's why it's no longer available out of the box. However, you can always add it back yourself and make it available in twig:

```
$variables['site_name'] = \Drupal::config('system.site')->get('name');

```
> 10 votes

# Answer
It looks like you can also use the following technique with twig\_tweak

```
{{ drupal_config('system.site', 'name') }}

```
> 7 votes

---
Tags: 8
---


title: Setting up tours

text:
# Question
Title: Setting up tours
I think I have two pretty straight questions about the tours and tours ui module but I can't seem to find the answers. Sorry for putting them in one post it seems more logic this way.

1. How can I create a custom tours button to call the tour on the current page. The default button is shown in my admin menu but I want it to show to people who don't have access to the admin menu as well. I know I can do this with a simple `<a href="/page/?tour=1">link</a>` but this makes the page reload and this doesn't happen with the default button. So there must be another way.
2. I have to insert a route for the page where the tour should be shown. The route I can find for my content type page is `entity.node.canonical` but I think this is the route to all node pages. Is there a way to make it specific for one content type page?

# Answer
## Question 1

If you look in tour module, there are a js/tour.js file with the logic. You could use it to figure out how it works.

```
Drupal.behaviors.tour = {
attach: function attach(context) {
  $('body').once('tour').each(function () {
    var model = new Drupal.tour.models.StateModel();
    new Drupal.tour.views.ToggleTourView({
      el: $(context).find('#toolbar-tab-tour'),
      model: model
    });

    model.on('change:isActive', function (model, isActive) {
      $(document).trigger(isActive ? 'drupalTourStarted' : 'drupalTourStopped');
    }).set('tour', $(context).find('ol#tour'));

    if (/tour=?/i.test(queryString)) {
      model.set('isActive', true);
    }
  });
 }
};

```

When you talk about default button, i think you are refering to '#toolbar-tab-tour' button, so you could write a js file following this example.

## Question 2

You are right. Tipically,you could work with this route using paramenters to build URL. For example:

```
$url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 1], $options)

```

But you can't add these params in module Tour UI. I think the easiest approach is build a simple module and create your own route to map a node. It should be fast.

Here the link for more infomation to build a module
> 2 votes

---
Tags: 8
---


# Question
Title: Adding #ajax callbacks to form elements in HOOK_form_alter()
I'm trying to add an #ajax callback to a select element on a form that is created in another module on a Drupal 8.x site. When I add the #ajax callback using HOOK\_form\_alter() in my module, the Ajax callback starts running and the Ajax throbber appears after changing the selection in the ajaxified select element, but then an exception is thrown and my callback function is never called:

```
Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\HttpException: "The specified #ajax callback is empty or not callable." at /var/www/drupal/public_html/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php line 70

```

It seems the \['#ajax'\]\['callback'\] is not available in FormAjaxResponseBuilder.php when the callback was added using HOOK\_form\_alter. If I use the exact same code (except the $this pointer) in my own custom form in buildForm(..) it works as expected.

Is this by design or is there another way to attach an ajax callback to an existing form's elements?

The form that I'm trying to alter in my module's HOOK\_form\_alter is created with a code like that **in the other module's /modulename/src/Form/DefaultForm.php**:

```
/**
 * Class DefaultForm.
 */
class DefaultForm extends FormBase {

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $form['example_select'] = [
            '#type' => 'select',
            '#title' => $this
                ->t('Select element'),
            '#options' => [
                '1' => $this
                    ->t('One'),
                '2' => [
                    '2.1' => $this
                        ->t('Two point one'),
                    '2.2' => $this
                        ->t('Two point two'),
                ],
                '3' => $this
                    ->t('Three'),
            ],

            //removed the callback from this form declaration. it works when ajax
            //event is added here.
            //trying to add ajax callback in form_alter in .module file instead.
            //'#ajax' => [
            //    'callback' => [$this, 'ajaxCallback'],
            //    'wrapper' => 'ajax-callback-target',
            //]
        ];

        $form['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
        ];

        return $form;
    }

```

Now back in my other module' ajaxfilters.module file I'm trying to add the ajax callback to the form above using HOOK\_form\_alter.

```
function ajaxfilters_form_alter(&$form, FormStateInterface $form_state, $form_id)
{

    if($form['#id'] == 'default-form')
    {

        //add ajax event to the select element
        $form['example_select']['#ajax'] = [
            'callback' => 'myCallback',
            'event' => 'change',
            'wrapper' => 'ajax-callback-target',
        ];

        //add container that receives the result of our callback
        $form['callback_target'] = [
         '#type' => 'container',
         '#attributes' => [
             'id' => ['ajax-callback-target'],
         ],
     ];

    } // EOF default-form

}

function myCallback(&$form, FormStateInterface $form_state)
{
  error_log("inside myCallback");
    $markup = '<h1>H3llo!</h1>';
  return ['#markup' => $markup];
}

```

When I now change the selection in the ajaxified select element, a throbber appears, but I end up with the exception described above.

I first thought it's a matter of scope and that my callback can't be accessed from FormAjaxResponseBuilder.php so I checked the code that throws the exception:

```
public function buildResponse(Request $request, array $form, FormStateInterface $form_state, array $commands) {
    // If the form build ID has changed, issue an Ajax command to update it.
    if (isset($form['#build_id_old']) && $form['#build_id_old'] !== $form['#build_id']) {
      $commands[] = new UpdateBuildIdCommand($form['#build_id_old'], $form['#build_id']);
    }

    // We need to return the part of the form (or some other content) that needs
    // to be re-rendered so the browser can update the page with changed
    // content. It is up to the #ajax['callback'] function of the element (may
    // or may not be a button) that triggered the Ajax request to determine what
    // needs to be rendered.
    $callback = NULL;
    if (($triggering_element = $form_state->getTriggeringElement()) && isset($triggering_element['#ajax']['callback'])) {
      $callback = $triggering_element['#ajax']['callback'];
    }

    $callback = $form_state->prepareCallback($callback);
    if (empty($callback) || !is_callable($callback)) {
      throw new HttpException(500, 'The specified #ajax callback is empty or not callable.');
    }
    $result = call_user_func_array($callback, [&$form, &$form_state, $request]);

```

The problem seems to be within here. **$form\_state-\>getTriggeringElement()** correctly returns the select element, where I added my ajax callback, but the **\['#ajax'\]\['callback'\]** is missing here, ie. isset($triggering\_element\['#ajax'\]\['callback'\]) returns false.

To rule out that's it's a problem with the scope I just added $callback = 'myCallback' right above the check if(empty($callback)). If I do so, my callback can successfully be executed.

How would I add an ajax callback to an existing form's elements if not by using HOOK\_form\_alter?

Thank you very much for your help!

# Answer
> 0 votes
The problem - as Charles Bamford pointed out in the comments - is in the form\_alter where the form id is checked.

```
if($form['#id'] == 'default-form')

```

The $form\['#id'\] changes each time the form is rebuilt when the Ajax callback happens. If you use above comparison, the code that attaches the Ajax callback will only be executed once the page is loaded, but not when the ajax callback happens.

This leads to the error:

```
Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\HttpException: "The specified #ajax callback is empty or not callable." at /var/www/drupal/public_html/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php line 70

```

To fix the problem change the comparison in form\_alter:

```
function ajaxfilters_form_alter(&$form, FormStateInterface $form_state, $form_id)
{

if( $form_id == 'default_form')
{

    //add ajax event to the select element
    $form['example_select']['#ajax'] = [
        'callback' => 'myCallback',
        'event' => 'change',
        'wrapper' => 'ajax-callback-target',
    ];

    //add container that receives the result of our callback
    $form['callback_target'] = [
     '#type' => 'container',
     '#attributes' => [
         'id' => ['ajax-callback-target'],
     ],
 ];

} // EOF default_form
}

```

---
Tags: forms, ajax
---


# Question
Title: How do I check Organic Groups group permissions from a custom module?
I'm trying to show or hide a button based on if a user has permission to post content to a group or not, but I don't seem to be able to call the `og_user_access` function from my custom module.

I've tried calling it directly while loading the module file:

```
module_load_include('module', 'og');
$allowed = og_user_access('group', $group->nid, 'create resource content');

```

Doing this crashes the page with no Apache error just a watchdog error of:

> Error: Class name must be a valid object or a string in entity\_get\_controller() (line 8066 of /data/home/rsdev/www/content/lnsres.rsdev.ca/web/includes/common.inc).

I've also tried using `module_invoke` like so:

```
$allowed = module_invoke('og', 'og_user_access', 'group', $group->nid, 'create resource content');

```

Calling the module like this doesn't crash the page, but it also doesn't return anything and if I add some `dpm()` calls in the contrib module function I notice it's not even being called. Doing some reading about `module_invoke` appears like it's mostly used to call hooks, which I don't think `og_user_access` is, so I'm not sure if that's even the correct path to take.

How should I check group permissions in OG from my custom module's code ?

EDIT: This is not a duplicate of Display data basing on the group permission because I'm not trying to use a permission I created. Also the only answer in that question doesn't work for me because as I explained, I can't call `og_user_access` without an error.

# Answer
> 1 votes
if your group entity is a node which I'm guessing it should be change your code to:

```
$gid // your group's node id.
$allowed = og_user_access('node', $gid, 'create resource content');

```

---
Tags: 7, organic-groups
---


# Question
Title: Results page template of Search API module
In Drupal 8, the default Search uses template file 'search-result.html.twig' to display results.

I have disabled the default search and enable module 'Search API' and Search API SOLR(used for Backend) to perform search in Drupal 8.

I need to customize the search results page of Search API not default search. How can I do this? The search-result.html.twig template doesn't work, with the Search API module.

# Answer
Search API filters and results are displayed using `views` \- so you need to override the views template.

So if you create a view page for your search called "Search API" (`search_api`) - and the machine name of that view is `page` \- then you can add the following file to your theme:

```
my_theme/templates/views-view--search-api--page.html.twig

```

You probably want to start by copying in the contents of `core/modules/views/templates/views-view.html.twig` into the above template file and start tweaking it from there.

---

For help creating the actual view you may find these links helpful:
> -3 votes

---
Tags: search
---


# Question
Title: How can I add a custom text field on the product detail page?
I want to add a custom text field on the product details page; its value will be shown on the cart and checkout pages. I have added the text field on the product, but it's not saved. What am I missing in the following code?

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'uc_product_add_to_cart_form_2') {
    $form['additional_guests'] = array(
      '#type' => 'textfield',
      '#title' => t("Additional Guest Names"),
    );
  }
}

```

How can I save this custom field and retrieve its value on the cart/checkout page?

# Answer
The uc\_attributes module, which has been part of Ubercart for 12 years, was specifically designed to handle this situation.

Enable the uc\_attributes module. Edit your product, then go to the "Attributes" tab and add a "textfield" type attribute to your product. Your customer will then be able to add text to the purchased product. This textfield will be displayed in the cart, on the checkout page, on the review order page, and in the admin/user view of the completed order.

In short, the correct way to do this is to "Use Attributes and set up a Textfield attribute on your product" as I stated in my previous answer (which was erroneously turned into a "comment" by some unknown user).

The Ubercart project page at https://www.drupal.org/project/ubercart gives links to detailed information about how to do this. Specifically, see: https://www.drupal.org/docs/7/modules/ubercart/all-about-products/product-attributes-and-options and the video tutorial at https://www.youtube.com/watch?v=fVDOqI7Gge4
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: How to get alter value of a views field programmatically
I've developed a Views field plugin that extracts the value from another field in the view in order to apply some math. The plugin works great at getting the original value of the field. However, I would like users to be able to get the **rewritten** value of a given field. I've been searching around, but can't seem to find any documentation on this.

With the following code I can get the value of another field:

```
public function getValue(ResultRow $values, $field = NULL) {
  parent::getValue($values, $field);

  $field = $this->options['data_field'];
  $value = $values->_entity->get($field)->value;

  // I have some logic here that's not necessary for this question.

  return $value;
}

```

What would I need to do within the above function to get the value of $field if $field had been rewritten via someone checking the "Override the output of this field with custom text" checkbox?

# Answer
> 1 votes
This is how I went about getting the "alter" value for my project:

```
if ($this->displayHandler->getHandler('field', $field)->options['alter']['alter_text'] == 1) {
  $value = $this->displayHandler->getHandler('field', $field)->options['alter']['text'];
}
else {
  $value = $values->_entity->get($field)->value;
}

```

# Answer
> 0 votes
Use advancedRender(), which renders an entity field respecting advanced settings including field rewrites:

```
$value = $this->view->field[$field_name]->advancedRender($values);

```

---
Tags: views, 8
---


# Question
Title: Programmatically change the weight of a form element
I have a user activation/registration form with different attribute like

Captcha and security questions which are coming from different modules.

I want to change the display order of form elements.

and i am using this code in my custom module

```
function security_question_form_user_register_form_alter(&$form, &$form_state) {
  if ($form_id == "create_account_form") {
    $form['#pre_render'][] = 'security_question_form_alter_weight';
  }
}

function security_question_form_alter_weight($elements) {
  $elements['questions']['#weight']= -47;
  return $elements;
}

```

It's not working. Can any one have any solution?

# Answer
You can do this directly inside `hook_form_alter`, like this:

```
function security_question_form_user_register_form_alter(&$form, &$form_state) {
  $form['questions']['#weight'] = -47;
}

```

Then there is no need to create a custom function to do it.

Another thing, you can't implement `hook_form_FORM_ID_alter` and then use `$form_id` inside that. You must implement either `hook_form_alter`, and check if the form id is the one you want, or implement `hook_form_FORM_ID_alter` and write the form id in the function name.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to set default value for entity reference field in hook_form_alter
following snippet doesn't set the default value.

```
 $form['field_image']['#default_value']='default';

```

I Have content type called image and I'm trying to set the default value for a reference to it in another content type. The above code doesn't work. Printing out the form variable doesn't make it seem like an easy task.

# Answer
You need to first check the structure of your form. Mine worked with the following:

```
$form['field_image']['widget'][0]['target_id']['#default_value'] = \Drupal\node\Entity\Node::load(2);

```

Cheers!
> 14 votes

# Answer
I had trouble with the above on 8.6.1 when using the *Entity browser widget* \- looking at the form edit values I found that this worked for me:

```
      $form['field_business_partner']['widget']['target_id']['#default_value'] = 'node:18';

```

Simple string. Note it didn't display the requisite node in the field but as this was being programmatically set it didn't matter in my use case.
> 1 votes

# Answer
You have to set three things, 1 - node default value, 2 - Entity browser default value , And 3 - Item , Which will show in edit form, Without Assigned the items it's not displayed in entity browser, While in backed it is set when we check by kint() var, demo code in my case:

```
    $form['field_related_stories']['widget']['target_id']['#default_value'] = "node:25507";
    $form['field_related_stories']['widget']['entity_browser']['#default_value'] = Node::load(25507);
    $form['field_related_stories']['widget']['current']['items'] = array();

```
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Cannot assign roles creating User through REST endpoint
Sidenote, already seen this page, doesn't seem to help: How to create user with role(s) through REST service?

I've setup a new endpoint on my platform to try to allow a 3rd party to create users on the site, I've connected it up and I'm testing it out through a REST client on Firefox. So far it seems to be working fine with the exception of applying the role to the new account.

According to the link pasted above, it needs to be set to:

```
{
  "name": "rest_user_1",
  "mail": "rest_user_1@test.com",
  "pass": "abc123",
  "status": "1",
  "roles": [
    "5",
    "6"
  ]
}

```

But that doesn't work, I've got the debugger enabled, and I can see from the response it seems to be coming back with this

```
Array
(
    [0] => Array
        (
            [name] => rest_user_1
            [mail] => rest_user_1@test.com
            [pass] => abc123
            [status] => 1
            [roles] => Array
                (
                    [0] => 5
                    [1] => 6
                )

        )

)

```

To me it looks like it's assigning the role IDs (5/6) as the values in an array, rather than the keys, so instead I tried writing my body in a different way:

My body at the moment is:

```
{
  "name": "rest_user_2",
  "mail": "rest_user_2@test.com",
  "pass": "abc123",
  "status": "1",
  "roles": {
    "5": "Role 1",
    "6": "Role 2"
  }
}

```

And the response in the log messages looks like:

```
Array
(
    [0] => Array
        (
            [name] => rest_user_2
            [mail] => rest_user_2@test.com
            [pass] => abc123
            [status] => 1
            [roles] => Array
                (
                    [5] => Role 1
                    [6] => Role 2
                )

        )

)

```

Which looks like exactly what I'd expect, but yet, still it hasn't applied the roles to my account. Can anyone help?

# Answer
> 1 votes
For other people reaching this post, the answer to this is to use some kind of authentication on the REST endpoint, that only allows trusted users to create new users.

Otherwise anonymous users would be able to create admins and crash the site.

So this code is correct,

```
"roles": [
  "5",
  "6"
]

```

but the problem is that the user calling the endpoint has to have the `administer permissions` and `administer users` permission to be able to set roles to users.

That can be done by setting a role that has those permissions and also has permission to call the endpoint.

oAuth could be used to do that.

---
Tags: 7, users, services
---


# Question
Title: How should the view data be defined when adding a custom filter to a field?
How to add a custom views filter handler for a specific field? answers on how to add a filter to a base field.

I'm looking to add a filter to a non base field. *(The field name is contact).*

Here's what I have so far:

```
/**
 * Implements hook_views_data_alter().
 */
function custom_contact_views_data_alter(array &$data) {
  $data['node__contact']['active_contact'] = [
    'title' => t('Active contact filter'),
    'filter' => [
      'title' => t('Active contact filter'),
      'help' => 'Filters node on active contact',
      'field' => 'contact_target_id',
      'id' => 'active_contact',
    ],
  ];
}

```

It is added, but it complains about group missing in the Views UI `Error: missing group`

**How should the views data be defined when adding a custom filter to a non-base field?**

# Answer
> 0 votes
You get the error `Error: missing group`.

You should be able to fix it by adding the group property, like this:

```
$data['node__contact']['active_contact'] = [
  'title' => t('Active contact filter'),
  'group' => t('Contact'), // Add this line.
  'filter' => [
    // ...
  ],
];

```

---
Tags: views, 8
---


# Question
Title: How can I load webform content inside a custom webform composite element?
I am using Drupal 8.7.3 and Webform 8.x-5.2.

I created a custom composite field in a multistep webform by extending WebformCompositeBase. My users select a subject in an earlier step. In this step I want to take the key of the user selection and request data based on this key.

```
class OtherExpectationsComposite extends WebformCompositeBase {
    public static function getCompositeElements(array $element) {
        return [
            'depending_content' => [
                '#markup' => 'content depending on earlier selections'
            ]
        ];
    }
}

```

How can I load the data insert to the form by the user in the earlier steps? `$element` doesn't contain anything helpful.

# Answer
> 0 votes
Finally I used the good old session.

My solution:

```
//mymodule.module
function mymodule_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $session = \Drupal::request()->getSession();
    $session->set('value_from_earlier_step', $form_state->get('value_from_earlier_step'));
}

//\src\Element\ExampleComposite.php
class ExampleComposite extends WebformCompositeBase {
    public static function getCompositeElements(array $element) {
        $session = \Drupal::request()->getSession();
        $expectations = $session->get('value_from_earlier_step');
    }
}

```

---
Tags: 8, webforms
---


# Question
Title: How to Inject entity object in EntityForm
We are trying to recreate https://www.drupal.org/project/menu\_editor for Drupal 8. So our idea is to extend `MenuForm` and then override the form in our own way to achieve what menu\_editor for Drupal 7 provides.

We created a custom module called menu\_editor and there we created a route.

```
  entity.menu.power_edit_form:
  path: '/admin/structure/menu/manage/power_edit/{menu}'
  defaults:
    _form: '\Drupal\menu_editor\Form\MenuEditor'
    _title_callback: '\Drupal\menu_ui\Controller\MenuController::menuTitle'
  requirements:
    _permission: 'access content'

```

Inside `MenuEditor`, we extend `MenuForm`.

```
namespace Drupal\menu_editor\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Menu\MenuLinkManagerInterface;
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\menu_link_content\MenuLinkContentStorageInterface;
use Drupal\menu_ui\MenuForm;
use Drupal\system\MenuInterface;

/**
 * Class MenuEditor.
 */
class MenuEditor extends MenuForm {

  var $menu;

  public function __construct(MenuLinkManagerInterface $menu_link_manager, MenuLinkTreeInterface $menu_tree, LinkGeneratorInterface $link_generator, MenuLinkContentStorageInterface $menu_link_content_storage)
 {
   // Trying to inject menu as suggested in https://drupal.stackexchange.com/questions/219431/entity-form-additional-arguments but not sure how we can get menu object over here
   $form_object = \Drupal::entityTypeManager()->getFormObject('menu', 'edit');
   $form_object->setEntity($this->menu);
   parent::__construct($menu_link_manager, $menu_tree, $link_generator, $menu_link_content_storage);
 }

 /**
  * {@inheritdoc}
  */
 public function getFormId() {
   return 'menu_editor';
 }

 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, MenuInterface $menu = NULL) {
   // Can get menu object over here but not sure how I can pass this in constructor.
   $this->menu = $menu;
 }

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

   parent::submitForm($form, $form_state);
 }

}

```

Whenever we are running this code, we get the following error.

> TypeError: Argument 1 passed to Drupal\Core\Entity\EntityForm::setEntity() must implement interface Drupal\Core\Entity\EntityInterface, null given

I do understand that using `$this` in the form will not help, since the constructor is called before, but I am not sure how to accomplish this.

# Answer
> 1 votes
Declare the entity form in the route via `_entity_form` instead of `_form`:

First add a form handler to the entity type:

*mymodule.module*

```
/**
 * Implements hook_entity_type_build().
 */
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['menu']
    ->setFormClass('poweredit', 'Drupal\mymodule\MyMenuForm');
}

```

Then add the form handler to the route:

*mymodule.routing.yml*

```
entity.menu.power_edit_form:
  path: '/admin/structure/menu/manage/power_edit/{menu}'
  defaults:
    _entity_form: 'menu.poweredit'
    _title_callback: '\Drupal\menu_ui\Controller\MenuController::menuTitle'
  requirements:
    _entity_access: 'menu.update'

```

Now Drupal upcasts the route parameter to an entity and adds it to the form object when it is instantiated.

This is similar to content entities, only that config entities have no form modes. See How to utilize custom form modes to edit a user entity?

---
Tags: 8
---


# Question
Title: How to assign a content type to a workflow programmatically?
is there any way that by code can assign a type of content to a workflow? I have reviewed the workflow module but I have not managed to find a method or a service that allows me to do it.

What I am trying to emulate is the action that makes this modal (programmatically not visually):

The only way I have found is by manipulating the workflows.workflow.myworkflow.yml

Per I'm trying to find a cleaner way.

Does anybody have an idea?

# Answer
> 1 votes
I found a way, I would like to know your opinion about how to do it.

No doubt you have to take into account additional validations, but basically to save a type of content to a workflow would be something like this:

```
/** @var \Drupal\workflows\WorkflowInterface $workflow */
$workflow = $this->entityTypeManager->getStorage("workflow")->loadByProperties(["id" => "editorial"])["editorial"];
$config = $workflow->getTypePlugin()->getConfiguration();
$config["entity_types"]["node"][] = "article";
$workflow->getTypePlugin()->setConfiguration($config);
$workflow->save();

```

At the moment I'm just setting contents types, for blocks it's something similar. Greetings.

---
Tags: 8, workflows
---


# Question
Title: How to make file description field as required?
I would like to set the file description as required. I tried it with this code:

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

  if ($form_id == 'node_news_homepage_edit_form') {

    $form['field_downloads']['widget'][0]['description_field']['#required'] = TRUE;
  }
}

```

But it didn't work. Could anyone help me?

# Answer
> 1 votes
The community is working to solve this problem: https://www.drupal.org/project/drupal/issues/2320877

While this isn't the part of the Drupal core, you can do the following:

```
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_news_homepage_edit_form') {
    $form['field_downloads']['widget'][0]['#process'][] = 'set_file_description_required';
  }
}

function set_file_description_required($element) {
    $element['description']['#required'] = TRUE;
    return $element;
}

```

# Answer
> 1 votes
Based on @DavidCzinege answer, a version that works for any form where the field appears and also for multivalued fields:

```
use Drupal\Core\Render\Element;

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {

  if (!empty($form['field_file']['widget'])) {

    foreach (Element::children($form['field_file']['widget']) as $el_index) {

      $form['field_file']['widget'][$el_index]['#process'][] = 'my_module_set_file_description_required';

  }

}

function my_module_set_file_description_required($element) {

  $element['description']['#required'] = TRUE;
  return $element;

};

```

---
Tags: 8, forms, files
---


# Question
Title: how to extend FormBuilder::processForm from multiple API endpoints in one class
I'm trying to consolidate my form processing by entity\_type, without rebuilding the forms (just using the default forms provided by Drupal.

I have dynamic routes pointing to a \_controller::method. I've tried:

* A. `\Drupal::service('entity.form_builder')->getForm($group_content, 'edit', $data)` but this just returns a render array, no instance.
* B. `\Drupal::formBuilder()->getForm('\Drupal\group\Entity\Form\GroupContentForm')` but this is the wrong class path and i can't figure out how I could reference any entity:bundle:id by any pattern (i've tried many)
* C. Changed the route to use `_form` or `_entity_form` extending `FormBase` (instead of a controller), but it seems these require the `buildForm` method to defined the form's full field list (which defeats the purpose of my question).

What is the best approach to expose edit/add/delete process handlers for multiple bundles / entity\_type in a single class?

# Answer
A. EntityFormBulder::getForm is just a shortcut for instantiating the form object, injecting the entity and building the render array. You can split this up:

```
  public function getForm(EntityInterface $entity, $operation = 'default', array $form_state_additions = []) {
    $form_object = $this->entityTypeManager->getFormObject($entity->getEntityTypeId(), $operation);
    $form_object->setEntity($entity);

    $form_state = (new FormState())->setFormState($form_state_additions);
    return $this->formBuilder->buildForm($form_object, $form_state);
  }

```

B. You have to inject the entity before you can build an entity form, see the steps above.

C. `_entity_form` is for integrating an entity form in a route, then the route parameter is upcasted and injected into the form automatically, see How to Inject entity object in EntityForm

The best approach is C. (standard pattern) and refactor the OOP code.

BTW if you don't find a OOP solution or if it is too complicated then you could simply add a custom process callback to `$form['#process']` in a form alter hook to all or specific entity forms.
> 0 votes

---
Tags: 8, forms, routes, dependency-injection
---


# Question
Title: Node access doesn't consider translation
I'm trying to check user access to node via this code:

```
 $node = Node::load($node_id);
 User::load(\Drupal::currentUser()->id());
 $node->access('view', $account)

```

It seems it doesn't check if user has access to node translation or not and it check only for first language of node -when we create node for first time.

For example if node is created in English as published and later in french as unpublished node access returns which user has access. If I update English language to unpublished and french to published, node-\>access returns false;

So node\_access doesn't consider translation? How we can check for translations too?

# Answer
> 1 votes
You can just call `getTranslation` like this:

```
$node_translation = $node->getTranslation('LANGCODE');

```

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


title: How to save file to different server?

text:
# Question
Title: How to save file to different server?
I want to specify a different file system remote server path. So that if I upload a file then this should be served from different remote server. I am using Drupal version 8.

# Answer
> 2 votes
You'll need a custom Stream Wrapper, which provides read/write operations to your remote file system (those docs are for Drupal 7, but the concept, if not implementation, is identical).

Fortunately, for Drupal 8 someone's written a stream\_wrapper\_example module, which contains a lot of boilerplate code for re-use.

There are also a bunch of existing community-supplied stream wrapper modules, a Google search like "drupal stream wrapper modules" will list them all for you. Obviously whether or you can re-use any of those depends on exactly what you mean by "remote", and how you're implementing the connection.

# Answer
> 0 votes
You can simply use a NFS and configure the file system to this one. No need to develop a streamWrapper with this method.

---
Tags: 8, files
---


# Question
Title: How do I get the base URL from the feed content?
Basically, I'm using the Aggregator module to import content from an RSS feed. The content is just a bunch of articles. I display this content in a view.

This is my current output, it shows the title and the date in a jcarousel. The thing I'm missing is the webpage source.
Currently, source url in views will have me a full link like:
**https://whatiwant.com/the-article-name-i-dont-want**
From the above, all I want to display is:
**whatiwant.com**

Here are my view settings:

I have tried adding different types of fields but none of them see to return the right value. Is there any way to perhaps strip the whole source url down to the base of it? I was thinking maybe it could be done programmatically however I need someone to point me in the right direction.

# Answer
> 2 votes
A way to do this would be to override the proprocess function get the domain like this:

```
function MY_MODULE_preprocess_views_view_field(&$variables) {
  $field = $variables['field'];

  if ($field->field == 'MY_LINK_FIELD_NAME') {
    $url = $variables['field']->getValue($variables['row'])[0];
    $parse = parse_url($url);
    $variables['output'] = $parse['host'];
  }
}

```

---
Tags: views, 8, feeds
---


title: Add theme color palette picker

text:
# Question
Title: Add theme color palette picker
I have a multisite in Drupal 8 eg. same codebase, differrent db. The client is asking for different color scheme for each subsite. I was thinking of implementing somehow Bartik's color picker, but have no idea how. The current theme is not derived from Bartik. O the question is how can I implement color picker in my custom subtheme?

Thanks

# Answer
This is done by the color module which is a part of Drupal core.

> The Color module allows users with the Administer site configuration permission to quickly and easily change the color scheme of themes that have been built to be compatible with it. In order for the color module to work, a theme must be specifically designed to use the color changing features.

Here's a great guide to integrate to the color module in Drupal 8.

Integrating the color module into your drupal 8 theme
> 2 votes

---
Tags: 8, theming
---


# Question
Title: How to remove the global library from specific page??
How to remove the global library from specific page ?

I want to rearrange java script files.

# Answer
You need to implement hook\_page\_attachments\_alter().
> 2 votes

# Answer
Yes, it's very simple to use the Hook\_page\_attarchment\_alter() Please see the following code it may help you.

```
    function modulename_page_attachments_alter(array &$attachments) {

    // Conditionally remove an asset.
    $current_path = \Drupal::service('path.current')->getPath();
    $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    if ($result == "/<url slug>" ){
      if (in_array('<theme name>/global-styling', $attachments['#attached']['library'])) {
        $index = array_search('<theme name>/global-styling', $attachments['#attached']['library']);
        unset($attachments['#attached']['library'][$index]);
      }
    }

}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Is different checkout-flow per product possible?
I've tried finding a solution to this myself, but have so far been very unlucky in that regard.
To save you checking the tags, this question is about:

* Drupal Commerce 8.x-2.0-beta6
* Drupal 8.2.7

**Question** I want different checkout flows on different products, and while I can find plenty of documentation on how to create these, I cannot find anywhere, how you tell the product which flow it should use.

I have tried searching, going to every commerce backend page on my install, searching through the questions here, and looked at commit messages in the hope that they would shed light on it.

Can anyone help me with this? I would greatly appreciate it.

Thanks in advance.

# Answer
> 2 votes
You need to implement a checkout flow resolver.

Look at the default resolver for an example: https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/checkout/src/Resolver/DefaultCheckoutFlowResolver.php And don't forget the matching services.yml entry: https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/checkout/commerce\_checkout.services.yml#L7 (You don't need to set the priority on yours though, it's -100 here so that DefaultCheckoutFlowResolver runs last)

# Answer
> 0 votes
Although above answer is marked I will give more verbose info. You need to make a resolver service so it can "hook" into commerce\_checkout.checkout\_flow\_resolver service collector

```
  commerce_checkout.chain_checkout_flow_resolver:
    class: Drupal\commerce_checkout\Resolver\ChainCheckoutFlowResolver
    tags:
      - { name: service_collector, call: addResolver, tag: commerce_checkout.checkout_flow_resolver }

```

, how that works, you can find here more about it. https://www.drupal.org/docs/8/api/services-and-dependency-injection/service-tags

Once you have that and resolver uses your service instead of default one(works on first come first serve basis), you will be able to make custom flow depending on your code, for example in your resolve method you could have something like this

```
if ($free && $numerical) {
  return CheckoutFlow::load('direct');
}
// If numerical product but non free, go to to the download checkout
elseif (!$free && $numerical) {
  return CheckoutFlow::load('download');
}

```

there is a good example how to do that here in this tutorial https://www.flocondetoile.fr/blog/working-drupal-commerce-2-checkout-flows

and more on commerce resolvers can be found here https://docs.drupalcommerce.org/commerce2/developer-guide/core/understanding-resolvers

EDIT: Also to acutally use a resolver you need to either create it in UI https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-flow

or add it into config/install, check here for example https://www.drupal.org/project/commerce\_stripe\_payment\_request\_button

---
Tags: 8, commerce
---


title: Adding Custom Link as View Fields

text:
# Question
Title: Adding Custom Link as View Fields
I want to add a custom link to the View field set for linking to the "Details" part. The link should be `/event/{{ nid }}` and the result should look like the following.

I found two modules called Custom Views Link / Views Entity Form Field that seems can implement the need but I don't know how to configure it.

Any help?

# Answer
If you want to construct the href attribute yourself then you can simply add the ID field to your Views, but use the `Rewrite results` setting.

You can use the "Output as link" option where you only construct the HREF part of the link and Drupal does the rest `event/{{ nid }}` (you can lookup the correct token below under Replacement patterns).

Or you can use the "Override the output" option where you construct the entire anchor element: `<a href="/event/{{ nid }}">Details</a>`.

If you're linking to nodes that are in your views rows then you can add the Link to Content field to directly link to content, without having to construct it through NID.
> 1 votes

---
Tags: views
---


# Question
Title: Attach different CSS classes to first and second link
I have a Paragraph type 'Call to action' with one link field `field_link`.

I have another Paragraph type where I call the 'Call to action' paragraph as an `Entity reference revisions` field. With `Allowed number of values` set to **2**.

So the editor is able to insert two Call to action links.

I want to attach **2** specific CSS classes to both links:

On the first link:

```
<a href="" class="button-one">Button one</a>

```

On the second link:

```
<a href="" class="button-two">Button two</a>

```

How do I loop through, so I am able to attach different classes?

**Update:**

In `paragraph--call-to-action.html.twig` I added:

{% block paragraph %}

{% for item in content.field\_link %} {% if loop.index == 1 %} Button one {% elseif loop.index == 2 %} Button two {% endif %} {% endfor %}

{% endblock paragraph %}

But now it's rendering always the 2 buttons? What's wrong here?

# Answer
> 1 votes
I figured how to loop through an entity reference field. Because I am looping from inside a paragraph twig through another paragraph (entity reference) I have to loop the children:

```
{% for item in content.field_name|children %}

```

So the `children` did the trick! Then you can do something like:

```
{% set link_class = loop.index == 1 ? 'primary' : 'secondary' %}

```

# Answer
> 0 votes
You can create a custom twig template to the call to action paragraph type.

Some code like this might work:

```
{% for item in content.field_link %}
  {% if loop.index == 1 %}
    {% set class == 'button-one' %}
  {% elseif loop.index == 2 %}
    {% set class == 'button-two' %}
  {% endif %}
  <a class="{{ class }}" href="{{ item.url }}">{{ item.title }}</a>
{% endfor %}

```

When creating a for loop in twig you always have the `loop.index` available. Loop.index is 1 indexed thats why you have to check if index is 1 or 2.

# Answer
> 0 votes
You are limiting the number of links via the Drupal UI, plus you don't have to style `instance99` if you had more than two links.

I would keep it simple.

**Twig**:

```
{% for item in content.field_link %}
  <a href="" class="button instance{{ loop.index }}">
    Button one
  </a>
{% endfor %}

```

**Styles**:

```
a.button {
  background: #f3f3f3;
  color: #333;

  &.instance1 {
    color: #444;
  }

  &.instance2 {
    color: #555;
  }
}

```

Adding an additional class will provide better scalability as well.

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


# Question
Title: Hooking into page specific instance of checkout flow form
I'm working on manipulating the buttons used for the checkout flow of using D8 Commerce 2.
I'm using `MYMODULE_form_commerce_checkout_flow_multistep_default_alter` but its changing both the form buttons on the order information page and the review page.
I want to have different buttons on these two pages.
Is there a way when using a hook to manipulate a form to set it so its page specific?

# Answer
Conditionals are still the answer, but turns out there's an easier way that doesn't involve getting the current path:

```
function MYMODULE_form_commerce_checkout_flow_multistep_default_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form['#step_id'] == 'order_information') {
    Do stuff to the order information page form.
  }
  if ($form['#step_id'] == 'review') {
    Do stuff to the review page form.
  }
}

```
> 0 votes

---
Tags: 8, forms, commerce, hooks
---


title: Get unsaved node from route parameter

text:
# Question
Title: Get unsaved node from route parameter
**What I want:** In `hook_media_presave` I want to set a field value according to the same field on the referring node.

By the `referring node`, I mean the node where the media entity is created through an entity reference field.

I don't know if this is possible at all, but if it is, then how?

My current approach is to get the node from the route like this inside the presave hook:

```
$node = \Drupal::routeMatch()->getParameter('node');

```

**My problem:** The node I get from the `routeMatch` doesn't contain the new changes. Is there a way to somehow get them using the `routeMatch`, or is there another way to get the node.

I thought maybe the media entity had some kind of `getReferringEntity()` method, but no.

Is this the correct approach, or am I wrong?

# Answer
With the help from @Clive I found a solution:

```
/**
 * Implements hook_node_update().
 */
function MY_MODULE_node_update(\Drupal\node\NodeInterface $node) {
  foreach ($node->getFieldDefinitions() as $definition) {
    if (!in_array($definition->getType(), ['entity_reference', 'entity_reference_revisions'])) {
      continue;
    }
    if (!$definition->getSetting('target_type')) {
      continue;
    }
    if ($definition->getSetting('target_type') == 'media') {
      $media = $node->{$definition->getName()}->entity;
      if ($media) {
        $media->groups->target_id = $node->groups->target_id;
        $media->save();
      }
    }
    if ($definition->getSetting('target_type') == 'paragraph') {
      $paragraph = $node->{$definition->getName()}->entity;
      if ($paragraph) {
        MY_MODULE_update_media_items($paragraph, $node->groups);
      }
    }
  }
}

/**
 * Set groups on all media items referenced in a paragraph.
 *
 * @param $paragraph
 *   The paragraph.
 * @param $groups
 *   The groups to set.
 */
function MY_MODULE_update_media_items($paragraph, $groups) {
  foreach ($paragraph->getFieldDefinitions() as $definition) {
    if (!in_array($definition->getType(), ['entity_reference', 'entity_reference_revisions'])) {
      continue;
    }
    if (!$definition->getSetting('target_type')) {
      continue;
    }
    if ($definition->getSetting('target_type') == 'media') {
      $media = $paragraph->{$definition->getName()}->entity;
      if ($media) {
        $media->groups->target_id = $groups->target_id;
        $media->save();
      }
    }
    if ($definition->getSetting('target_type') == 'paragraph') {
      $paragraph = $paragraph->{$definition->getName()}->entity;
      if ($paragraph) {
        MY_MODULE_update_media_items($paragraph, $groups);
      }
    }
  }
}

```
> 2 votes

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