# Question
Title: Setting custom block.html.twig templates in preprocess function (not based on twig naming scheme)
I've created several block plugins each with their own block form. My goal is to make it so you can select what template to use based on a field in the blockForm. I understand that I can change a block template within the build function by specifying the '#theme' but that refers to the content. I want to change block.html.twig template being used that surrounds the content. I also understand that I can specify the block template by using the naming scheme like block--block-name.html.twig but I want to be able to select the template within a preprocess function. Below is my attempt.

In mytheme.theme I have

```
function mytheme_theme($existing,$type,$theme,$path){
    return [
        'wide_grid_block' => [
            'variables' => [
                'test' => 'Test default value',
            ],
        ]
    ];
}

function mytheme_preprocess_block(&$vars){
      $vars['#theme'] = 'wide_grid_block';
}

```

and in templates/block/wide-grid-block.html.twig I have

```
Testing: {{ test }}

```

I assumed the what should occur is that every block should use the wide-grid-block.html.twig file. But they're all still using block.html.twig.

How do I specify a custom block template in a preprocess function?

UPDATE: I've also tried using a theme\_suggestions\_block\_alter hook but I get a white screen when attempting to do so

```
function alltechcom2017_theme_suggestions_block_alter(array &$suggestions, array $variables) {
$suggestions[0]= 'wide_grid_block';
}

```

And I've tried with and without the \[0\]

UPDATE 2: I've managed to add to the suggestions by using

```
$suggestions[] = 'wide_grid_block';

```

The issue I had before with the white screen was because the file was in the wrong location. So I know drupal can see it, I just need it to be the most desired one in the list of possible templates.

In the debug info I see

```
<!-- FILE NAME SUGGESTIONS:
   * block--product-selector.html.twig
   * wide-grid-block.html.twig
   x block.html.twig
-->

```

And I have a block.html.twig and a wide-grid-block.html.twig. Why is it using block.html.twig instead? It's acting as if my file doesn't exist. I looked at this https://sqndr.github.io/d8-theming-guide/theme-hooks-and-theme-hook-suggestions/theme-hook-suggestions.html and it appeared like I was on the right track.

UPDATE 3: I've added

```
function mytheme_theme($existing,$type,$theme,$path){
    return [
        'wide_grid_block' => [
            'path' => drupal_get_path('theme','mytheme').'/templates',
            'template' => 'wide_grid_block',
        ],
    ];
}

```

but still no luck

# Answer
I managed to get it working by using

```
function mytheme_theme($existing,$type,$theme,$path){
        return [
                'wide_grid_block' => [
                        'path' => drupal_get_path('theme','mytheme').'/templates',
                        'template' => 'wide-grid-block',
        'render element' => 'elements',
        'preprocess functions' => ['template_preprocess','template_preprocess_block','comment_preprocess_block','mytheme_preprocess_block'],
                ],
        ];
}

function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
if($variables['elements']['#configuration']['id'] == 'page_title' || $variables['elements']['#configuration']['id'] == 'product_selector'){
        $suggestions[] = 'wide_grid_block';
}

```
> 1 votes

# Answer
I just ran into a very similar issue, where theme suggestions were displaying my custom block template, and the template was present in my theme, but wasn't being used.

```
<!-- FILE NAME SUGGESTIONS:
   * block--my-custom-template.html.twig
   * block--views-block.html.twig
   x block.html.twig
-->

```

In my case, I wanted to add a template suggestion based on the tag (my-custom-template) of the view that the block is displaying:

```
function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  // Add Views tag suggestions for block templates
  if ($variables['elements']['#base_plugin_id'] == 'views_block') {
    $view = View::load($variables['elements']['content']['#view_id']);
    $suggestions[] = 'block__' . str_replace('-', '_', $view->get('tag'));
  }
}

```

Without the str\_replace, the $suggestion is 'block\__my-custom-template' when it needs to be 'block\__my\_custom\_template' in order for the template to be found and called correctly.

I know it doesn't 100% match the original issue, but I wanted to share for others and for me when I come searching for this again in a year!
> 1 votes

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


# Question
Title: New line item every time an item is added (avoid grouping)
How can I avoid grouping of the same items (products configured identically) to be grouped in the same line item with a quantity count?

I want every single item, even if an identical already exists in the cart, to be its own line item with its own ID.

I tried several rules that fire when a new product is added to cart, when a line item is updated, tried duplicating, re-adding... even tried a timestamp field which would be different for every time a user adds an item, which should result in a new line item being created - but this is just too much of a hack for me.

Is there any clean way to create a new line item for every item in the cart?

# Answer
You can just toggle the setting on your Add to Cart form display formatter to turn off combining like items in the cart.
> 6 votes

# Answer
I would look into using hook\_commerce\_cart\_product\_comparison\_properties\_alter or any other hooks that will allow you to alter the line item before it being added to the cart such as hook\_commerce\_product\_calculate\_sell\_price\_line\_item\_alter.

Using **hook\_commerce\_product\_calculate\_sell\_price\_line\_item\_alter()** (or similar hooks), you can try to change the 'add\_to\_cart\_combine' property of the line item:

```
/**
 * Implements hook_commerce_product_calculate_sell_price_line_item_alter().
 *
 * Alter the 'add_to_cart_combine' property to always be FALSE.
 */
function example_commerce_product_calculate_sell_price_line_item_alter($product_line_item) {
  $product_line_item->data['context']['add_to_cart_combine'] = FALSE;
}

```

Using **hook\_commerce\_cart\_product\_comparison\_properties\_alter()** involves more work but looks a lot less "hacky". From Commerce Cart API:

```
/**
 * Allows modules to add additional property names to an array of comparison
 * properties used to determine whether or not a product line item can be
 * combined into an existing line item when added to the cart.
 *
 * @param &$comparison_properties
 *   The array of property names (including field names) that map to properties
 *   on the line item wrappers being compared to check for combination.
 * @param $line_item
 *   A clone of the line item being added to the cart. Since this is a clone,
 *   changes made to it will not propagate up to the Add to Cart process.
 */
function hook_commerce_cart_product_comparison_properties_alter(&$comparison_properties) {
  // Force separate line items when the same product is added to the cart from
  // different display paths.
  $comparison_properties[] = 'commerce_display_path';
}

```

This means, you can add another property to the comparison properties array that will be used to determine how products can be combined to existing line items in the cart. In that case, I would add a new property that will always be different for each line item being added (e.g. a timestamp, md5 hash):

```
function example_commerce_cart_product_comparison_properties_alter(&$comparison_properties) {
  // Force separate line items when the same product is added to the cart at different times.
  $comparison_properties[] = 'timestamp';
}

```

You'll have to make sure though that you have a timestamp field in your line item (either by adding through the field manager or programmatically attaching the field).
> 3 votes

# Answer
For anyone looking to do this (which there are a bunch of ppl..) I found a way to finally get this to work.

For starters, **turn off the Combine** options in your **Line Item** displays and **Product** displays.

Then install Rules Array Create module, this is key, since we need to work with a loop in Rules and the Quantity is a variable not an Array which is the only thing loops can work with.

Next, import this Rule.

```
{ "rules_split_quantity" : {
    "LABEL" : "Split Quantity",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_array_create", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "quantity" ], "op" : "\u003E", "value" : "1" } }
],
"DO" : [
  { "array_create" : {
      "USING" : { "size" : [ "quantity" ] },
      "PROVIDE" : { "array_added" : { "amount_array" : "Amount Array" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "amount-array" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "commerce_cart_product_add_by_sku" : {
            "USING" : {
              "user" : [ "site:current-user" ],
              "sku" : [ "commerce-product:sku" ],
              "quantity" : "1",
              "combine" : "0"
            },
            "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
          }
        }
      ]
    }
  },
  { "list_remove" : {
      "list" : [ "commerce-order:commerce-line-items" ],
          "item" : [ "commerce-line-item" ]
    }
      }
    ]
  }
}

```

Just to add you probably noticed the "List Remove" action. This removes the original line item with it's original quantity. Without this, if you added a product with qty 5, you would end up with 6 line items. 1 with a qty of 5, and another 5 with the qty of 1.

I also changed the cart View display to only show the Quantity, and not the Quantity Text which allows people to further change their qty in the cart.
> 1 votes

# Answer
If you are adding an item to cart programmatically in Drupal 8, you can set the combine option to false.

`$cart_manager = \Drupal::service('commerce_cart.cart_manager');
 $cart_manager->addOrderItem($cart, $order_item, false);`
> 1 votes

# Answer
Quick and dirty option :

File : commerce\_cart.module

Function : commerce\_cart\_product\_add($uid, $line\_item, $combine = TRUE)

$combine set to FALSE

Done.

Personally I'd create a custom module and use 'hook\_commerce\_cart\_product\_comparison\_properties\_alter'...
> 0 votes

---
Tags: commerce
---


# Question
Title: Custom post type form field to reference other content type field values
I have two custom content types.

1. *Comic books borrowed*, as an application form to borrow comics
2. Available comic books and their respective available issues

My goal is to have the website editors record each comics with available issues (each having different issues, this is collected with a simple text field and any issue field can be added to a comicbook). The other, Application form is for (registered) site visitors wanting to borrow the comic books.

I would like to have the application form to be able to refer a comic and dynamically load their respective available issues. I use Drupal 8 and would like to do this with as little coding as possible since I think there are enough modules out there, I just cannot grasp the solution for the following case. *I can add the list of available comic books by node reference.* What I am having problem is to display the available issues for the selected comic book dynamically (so when the customer selects Batman from the comics list, the I would like to show the available issues related to the comic book).

Is there a UI-controlled method to do this with fields and/or entity reference? Should I use Views reference field or Entity reference view? (How?) Thanks any feedback on this :)

# Answer
> 0 votes
> Is there a UI-controlled method to do this with fields and/or entity reference?

No, I don't think so.

Especially not when it's just a text field but also not when it's a more structured type of content. That kind of dynamic refresh/selection update requires custom code. You need to implement a module that alters the form with an ajax element that triggers a form rebuild that updates a second select based on what's in the other.

See How to dynamically populate select options? and How to fill select options based on previous select? for related questions. The first is for Drupal 7 but conceptually, it's still basically the same in Drupal 8.

Explaining everything in detail is too complex for the format of this site. You'll need to get started with tutorials on creating a module, form system, AJAX and so on, and then ask specific questions if you're stuck.

---
Tags: views, 8, entities
---


title: Get all commerce product types

text:
# Question
Title: Get all commerce product types
I am creating a module that needs to add a number of fields to all commerce product types. In Drupal 7, I used the function commerce\_product\_types() to get all the types and than used that, but I can't seem to find the equialent in Drupal 8. So, I have commerce product type 'default', but I also have 'radios', and 'computers'. I don't know how many types there will be on the website, so it needs to automatically detect all types.

# Answer
> 2 votes
Use this:

```
/**
* Get all product types
* @return array
*/
public function getProductTypes() {
   $product_types = \Drupal\commerce_product\Entity\ProductType::loadMultiple();
   return array_keys($product_types);
}

```

---
Tags: 8, commerce
---


# Question
Title: Class not found in drush command definition
In the drush command definition hook for the Node Revision Delete project I have the following code:

```
use Drupal\node_revision_delete\Utility\Time;

...

function node_revision_delete_drush_command() {
  $values = array_keys(Time::convertWordToTime());

```

The namespace exists and is in the correct place but once I use `drush cr` I got this error:

```
Error: Uncaught Error: Class 'Drupal\node_revision_delete\Utility\Time' not found in /Users/adriancid/Sites/drupal84-test/modules/drupal.org/node_revision_delete/node_revision_delete.drush.inc:34

```

It's weird because I call the same function in the line 179 for the `drush nrd-st` command and is working fine:

```
Time::convertWordToTime();

```

Trying to understand what happens I tried to use an Utility function from the Core in the drush definition command hook and works fine without problem, but with my function call it doesn't works.

Any idea about class not found problem?

# Answer
As @Berdir says it seems Drupal is not fully bootstrapped when the `hook_drush_command()` is called as I tried to use a service defined in a custom module and I get the following error:

```
\Drupal::$container is not initialized yet.

```

So the solution for the moment is hardcode the values that should be returned by the function.
> 0 votes

---
Tags: 8, drush
---


# Question
Title: Get values from unlimted field programmatically in node_presave hook
I have created class content type and set *Allowed number of values to **unlimited**"* to "Division" field Now I want to get "Division" field values programmatically in node presave hook I'm using below code.

```
function example_node_presave(Drupal\Core\Entity\EntityInterface $node){
  if($node->bundle() == "class") {
     $getDivison = $node->get('field_class_division')->target_id;
   }
}

```

If i print $getDivison then I get 739 only.

# Answer
> 4 votes
You can loop over a field object and access each item separately, that's often more convenient than going through getValue():

```
function example_node_presave(Drupal\Core\Entity\EntityInterface $node){

  if($node->bundle() == "class") {
     foreach ($node->get('field_class_division') as $item) {
       echo $item->target_id;
     }
   }
}

```

And to access a specific delta (that's what the index in a multi-value field is called in the Field API), you can access it like an array as well, but you need to make sure that the deltas exist:

```
echo $node->get('field_class_division')[1]->target_id

```

See https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for a very useful cheat sheet on how to work with the Entity Field API.

# Answer
> 2 votes
You can use:

```
function example_node_presave(Drupal\Core\Entity\EntityInterface $node){

  if($node->bundle() == "class") {
     // Use getValue() to get multiple values in array.
     $getDivison = $node->get('field_class_division')->getValue();
   }
}

```

---
Tags: 8, nodes
---


title: Unable to migrate users

text:
# Question
Title: Unable to migrate users
I have been using the migrate module to migrate users from Drupal 7.59 to Drupal 7.59. I encounter the following error.

```
Migration for <em class="placeholder">NonDomainUserMigration</em> failed with source plugin exception: <em class="placeholder">SQLSTATE[42S22]: Column not found: 1054     [error]
Unknown column 'pgid' in 'on clause'</em>, in <em class="placeholder">/app/includes/database/database.inc</em>:<em class="placeholder">2227</em>

```

What could be the issue? I can't find any pgid column in the drupal database.

the following is my User migration code

```
<?php
abstract class NonDomainBaseMigration extends Migration {

  // A Migration constructor takes an array of arguments as its first parameter.
  // The arguments must be passed through to the parent constructor.
  public function __construct($arguments) {
    parent::__construct($arguments);

    // With migrate_ui enabled, migration pages will indicate people involved in
    // the particular migration, with their role and contact info. We default the
    // list in the shared class; it can be overridden for specific migrations.
    $this->team = array(
      new MigrateTeamMember('Moses Liao', 'moseslgz@sph.com.sg',
        t('Tech Lead')),
    );

    Database::addConnectionInfo('legacy', 'default', array(
      'driver' => 'mysql',
      'database' => 'zaobao_drupal',
      'username' => 'root',
      'password' => 'password',
      'host' => 'mysqldb',
      'prefix' => '',
    ));
  }
}

class NonDomainUserMigration extends NonDomainBaseMigration {
  public function __construct($arguments) {

    parent::__construct($arguments);
    $this->description = t('Legacy Zaobao Drupal 7 system Users');

    $query = Database::getConnection('default', 'legacy')
    ->select('users', 'u')
    ->fields('u');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationUser();

    $source_key = array(
      'pgid' => array('type' => 'int',
                      'unsigned' => TRUE,
                      'not null' => TRUE,
                      'description' => t('Source ID'),
                     )
    );
    $this->map = new MigrateSQLMap($this->machineName, $source_key,
      MigrateDestinationNode::getKeySchema(), 'legacy', array('track_last_imported' => TRUE));

    $this->addSimpleMappings(
      array(
        'uid',
        'name',
        'pass',
        'mail',
        'theme',
        'signature',
        'signature_format',
        'created',
        'access',
        'login',
        'status',
        'timezone',
        'language',
        'picture',
        'init',
        'data',
      )
    );
  }
}

```

# Answer
its seems to me that `pgid` is wrong. Should be `uid` for users
> 0 votes

---
Tags: users, migrations
---


# Question
Title: How can I programmatically create a link/URL with querystrings set from parameters?
In Drupal 8 I customize the filter in the block in the sidebar menu. When the user clicks on the option in the block, I need to pass his choice to the URL.

```
$this->args = \Drupal::request()->query->all();
$args[$id] = $value;
$url = $this->url = Url::fromRoute('<current>');
$url->setOptions(array('query' => $args));
$link = '<a href="' . $url->toString() . '">' . $label . '</a>';

```

And in the end, my URL looks like

```
 drupal/page_view?content_type=type

```

but I need my URL to look like

```
drupal/page_view?content_type%5Btype%5D=type

```

Do you know how can I modify my code?

# Answer
> 5 votes
Let's say if your `$args` is an array like below:

```
$args['content_type'] = 'type';

```

Then you have to append `type` to it rather than just giving your `$id to $args`

```
$args['content_type'] = ['type' => '123'];

```

Then your overall query will be like:

```
$this->args = \Drupal::request()->query->all();
$this->args = [$id => $value];
$url = $this->url = Url::fromRoute('<current>');
$url->setOptions(array('query' => $args));
$link = '<a href="' . $url->toString() . '">' . $label . '</a>';

```

# Answer
> 2 votes
You try code :

```
$options = ['absolute' => TRUE];
$url = Url::fromRoute('entity.node.canonical', ['node' => 526,'destination'=>'router_back'], $options);
$link = Link::fromTextAndUrl('Here is the link', $url)->toString();

```

Result link:`node/526?destination=router_back`

You see more Url::fromRoute

---
Tags: 8, uri
---


title: How to set admin theme for a route?

text:
# Question
Title: How to set admin theme for a route?
According to Drupal handbook route definition accepts parameter called `_theme`. Unfortunately this parameter is documented as *"TODO"*.

Can this be used to force admin theme for the route? Is it possible to inject config parameter with admin theme name here?

It appears that other solution is to use Theme negotiator however the `_theme` parameter looks very tempting and way simpler to use.

# Answer
You're looking for the \_admin\_route option:

```
aggregator.feed_add:
  path: '/aggregator/sources/add'
  defaults:
    _controller: '\Drupal\aggregator\Controller\AggregatorController::feedAdd'
    _title: 'Add feed'
  requirements:
    _permission: 'administer news feeds'
  options:
    _admin_route: TRUE

```
> 19 votes

# Answer
```
module.myroute:
  path: '/path/path2'
  defaults:
    _controller: 'Drupal\module\Controller\MyController::add'
    _title: 'Add element'
  options:
    _admin_route: 'TRUE'

```

You need to use ' ' around TRUE, if not, you will get 'InvalidArgumentException: Routing requirement for "options" must be a string'
> 5 votes

---
Tags: 8, routes
---


# Question
Title: Change the look and feel of the user registration form
What I've done so far is that I have copied the contents of the file `page.html.twig` into a newly created file `page--user--register.html.twig`.

But I don't know how to change the look and feel of the registration form.

# Answer
1)Alter theme suggestion in your-theme.theme file.

```
function hook_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

if ($hook == 'form' & !empty($variables['element']['#id'])) {
 $suggestions[] = 'form__' . str_replace('-', '_', $variables['element']  ['#id']);
}
}

```

2)Create **form--user-register-form.html.twig** in your themes template folder and make changes according to your requirement.

```
 <div id="login" class="ptb ptb-xs-60 page-signin">
<div class="container">
  <div class="row">
    <div class="main-body">
      <div class="body-inner">
        <div class="card bg-white">
          <div class="card-content">
            <section class="logo text-center">
              <h2>Register</h2>
            </section>
            <form class="form-horizontal ng-pristine ng-valid">
              <fieldset>
                <div class="form-group">
                  <div class="ui-input-group">
                    <label>Your username</label>
                    {{ element.account.name }}
                  </div>
                </div>
                <div class="form-group">
                  <div class="ui-input-group">

                    <label>Your email</label>
                   {{ element.account.mail }}
                  </div>
                </div>
                <div class="form-group">
                  <div class="ui-input-group">

                    <label>Your password </label>
                  </div>
                </div>
                <div class="form-group">
                  <div class="ui-input-group">

                    <label>Please confirm your password </label>
                    {{ element.account.pass }}
                  </div>
                </div>
                <div class="spacer"></div>
                <div class="form-group checkbox-field">
                  <label for="check_box" class="text-small">
                    <input id="check_box" type="checkbox">
                    <span class="ion-ios-checkmark-empty22 custom-check"></span>{{ element.terms_of_use }}
                </div>
              </fieldset>
            </form>
          </div>
             {{ element.form_build_id }} {# required #}
             {{ element.form_id }} {# required #}
          <div class="card-action no-border text-right"> <a href="#/page/signin">Login</a><a href="#/" class="color-primary">{{ element.actions.submit }}</a></div>
        </div>
      </div>
    </div>
  </div>
</div>

```
> 1 votes

# Answer
You do not need to change the page template if you only want to change to login form. Take a look at the rendered output. Maybe you can achieve your requirements by simple CSS changes in your theme.

If not, go for the templates of form, form-element, input, container.

Or, if you have a custom module, override the login form of the user module.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How do I assign a region to programmatically created block?
Hi after following this guide I was able to create multiple blocks. But I have couple of issues.

1. Blocks are not created instantly need to clear cache but cant find a way to do it instantly (solution might be clearing block cache but how ?).
2. I need to assign region to the block while creating itself but cant do so .
3. I want to have x content for x *block id* and y content for y *block id* cant write a filter condition as I cant get *block id* of the blocks.

Basically I want to achieve all the D7 module's functionality in D8.

If anyone have an idea please help me.

# Answer
> 2 votes
That's expected. You can do it from code if needed. The following are the steps to follow.

1. Settings definition is done as in block.block.test\_block.yml. Place that file, after editing it, in my\_module/config/install and you're set. A quick hack is managing the block settings manually in a local environment and export them from /admin/config/development/configuration/single/export.
2. Import your settings, which can be done using code similar to the following one.

```
use Drupal\Core\Config\FileStorage;

$config_path = drupal_get_path('module', 'my_module') . '/config/install';
$source = new FileStorage($config_path);
$config_storage = \Drupal::service('config.storage');
$block_config = 'block.block.test_block';
$config_storage->write($block_config , $source->read($block_config));

```

Block settings are theme dependent.

For dynamic allocation of blocks, you can load and alter the block entity like this.

```
use Drupal\block\Entity\Block;

$block = Block::load('test_block');
$block->setRegion('my_region');
$block->save();

```

---
Tags: 8, blocks
---


title: Exposed filter for file field

text:
# Question
Title: Exposed filter for file field
I have a content type with several file fields. I have a view listing nodes of that content type. Now I want to add an exposed filters for each file field to let users filter only those nodes which have a file attached to corresponding field (or not have, whatever they choose).

So, I see choice options like this:

* Any
* Has file attached
* No file attached

Is there a module for this? Or my only way is to write a custom Views filter?

# Answer
> 1 votes
Answering to myself :\]

Add a new filter for, say, `field_file:fid`, make it exposed and choose `Is not empty` operator.

It will not work :D It is a known Views issue. Luckily, comment #70 in that issue has a patch to fix this operator behavior, apply it and enjoy :)

# Answer
> 0 votes
I was able to work around it using **Grouped filters**.

I added Content File:fid filter and exposed it.

Then I selected Grouped filters option (instead of the Single filter).

In the table that appears where you can set your options, the first one is Any (default), in the second one I added

```
Label YES
Operator Is greater than
Value 0

```

and I removed the third table row as I didn't need it.

This filter works! It shows the filter with 2 options: Any and YES. Any is default and shows all results. If I select YES it only shows results that have a file attached :)

I also added Content: file among Fields so it's easy to test the filter.

# Answer
> 0 votes
My approach for this was based on experimentation on previous answer by prkos

My case included a image field with images uploaded to my site. So the file-path output for the field was - http://example.com/sites/default/files/001.png

In the views exposed filter, I have used **File: Path (grouped)** after adding *relationship for file*.

Now for the grouped options

```
- Any -
Yes | Operator: Length is greater than | Value: 0
No  | Operator: is empty (Null)        | Value: NULL

```

This works for me. This gives me a filter for whether an image field is empty or not.

---
Tags: 7, files, views
---


# Question
Title: Error on update from 2.3 to 2.8 and 2.7?
I'm using drupal commerce 2.3 and want to update to commerce 2.8.

I just copied the files to the new folder and get the error:

```
PHP Fatal error:  Uncaught Error: Class 'CommerceGuys\Addressing\AddressFormat\FieldOverride' not found in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php:272
Stack trace:
#0 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(206): Drupal\commerce_store\Entity\Store::baseFieldDefinitions(Object(Drupal\Core\Entity\ContentEntityType))
#1 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(171): Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions('commerce_store')
#2 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityManager.php(182): Drupal\Core\Entity\EntityFieldManager->getBaseFieldDefinitions('commerce_store')
#3 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(72): Drupal\Core\Entity\EntityManager->getBaseFieldDefinitions('commerce_store')
#4 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(118): Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenc in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php on line 272

Fatal error: Uncaught Error: Class 'CommerceGuys\Addressing\AddressFormat\FieldOverride' not found in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php:272
Stack trace:
#0 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(206): Drupal\commerce_store\Entity\Store::baseFieldDefinitions(Object(Drupal\Core\Entity\ContentEntityType))
#1 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(171): Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions('commerce_store')
#2 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityManager.php(182): Drupal\Core\Entity\EntityFieldManager->getBaseFieldDefinitions('commerce_store')
#3 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(72): Drupal\Core\Entity\EntityManager->getBaseFieldDefinitions('commerce_store')
#4 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(118): Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenc in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php on line 272
Drush command terminated abnormally due to an unrecoverable error.                                           [31;40m[1m[error][0m
Error: Uncaught Error: Class 'CommerceGuys\Addressing\AddressFormat\FieldOverride' not found in
C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php:272
Stack trace:
#0 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(206):
Drupal\commerce_store\Entity\Store::baseFieldDefinitions(Object(Drupal\Core\Entity\ContentEntityType))
#1 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(171):
Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions('commerce_store')
#2 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityManager.php(182):
Drupal\Core\Entity\EntityFieldManager->getBaseFieldDefinitions('commerce_store')
#3 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(72):
Drupal\Core\Entity\EntityManager->getBaseFieldDefinitions('commerce_store')
#4 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(118):
Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenc in
C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php, line 272

```

But when I go to : C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php

This file is just there.

I tried the same to goto commerce 2.7, but then same error applies.

Somebody any suggestion?

# Answer
> I just copied the files to the new folder

That's not how to update a Drupal 8 project - you need to use Composer.

Run `composer update` in your project root, and the old version of the address library (commerceguys/addressing), which is causing your current problem, will be upgraded alongside the modules.
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: How can I insert a variable into query condition?
I am writing a query, and the question is how can I insert an array variable into condition statement. So instead of having (1060,968,1106) I would like to place there an array.

```
$fields; // array with some predefined ids
$query = $this->connection->select('node', 'node');
$query->innerJoin('node__field_field', 'nfc', "nfc.entity_id=node.nid AND
                (nfc.field_field_target_id IN (1060,968,1106))");

```

I tried

```
$query->innerJoin('node__field_field', 'nfc', "nfc.entity_id=node.nid AND
                (nfc.field_field_target_id IN ".$fields." )");

```

But it doesn't work, could you please help me?

# Answer
> 1 votes
Outside of extreme circumstances, never, ever concatenate variables into an SQL string. You'll leave yourself open to SQL injection.

It feels like you should be using an entity query for this, but for the sake of the exercise, use a placeholder and pass the arguments in:

```
$args = [
  ':fields[]' => ['id_1', 'id_2', 'id_3'],
];
$query->innerJoin('node__field_field', 'nfc', 'nfc.entity_id=node.nid AND nfc.field_field_target_id IN (:fields[])', $args);

```

---
Tags: 8, database
---


title: How do I unlock a field?

text:
# Question
Title: How do I unlock a field?
In Drupal 7 it is possible to use:

```
$field_name = 'field_name';
$field = field_read_field($field_name);
$field['locked'] = 0; // 0: unlock; 1: lock.
field_update_field($field);

```

How to do this in Drupal 8?

# Answer
You need to load the related field storage config entity and change the locked status:

```
\Drupal::entityTypeManager()
  ->getStorage('field_storage_config')
  ->load('node.field_foo')
  ->setLocked(FALSE)
  ->save();

```

This is just an example - you should inject the entity type manager instead of calling the global version if contexts allows.
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Language Manager getCurrentLanguage returns default language instead
I am creating a multilingual D8 site, which 3 languages enabled.

In trying to display the currently active language, the snippet

```
$lang = \Drupal::languageManager()->getCurrentLanguage()->getName();

```

always returns the default language ( English ) even though the UI has switched to one of the alternative languages. The above line is called from the `mytheme.theme` file in `hook_preprocess_page`.

In the language switcher block, the correct language is getting the session-active is-active classes.

When referencing the documentation for D8.5 in the above method, in the code shown it very much shows like this is what the function does:

```
public function getCurrentLanguage($type = LanguageInterface::TYPE_INTERFACE)
{
  return $this
    ->getDefaultLanguage();
}

```

Am I missing something obvious here? Is there another way to get the current active language?

# Answer
> 2 votes
The method you've quoted is the default code for single language sites. For multilingual sites the default LanguageManager is replaced with `ConfigurableLanguageManager` and the method is overridden wtih this content:

*ConfigurableLanguageManager::getCurrentLanguage:*

```
public function getCurrentLanguage($type = LanguageInterface::TYPE_INTERFACE) {
  if (!isset($this->negotiatedLanguages[$type])) {

    // Ensure we have a valid value for this language type.
    $this->negotiatedLanguages[$type] = $this
      ->getDefaultLanguage();
    if ($this->negotiator && $this
      ->isMultilingual()) {
      if (!$this->initializing) {
        $this->initializing = TRUE;
        $negotiation = $this->negotiator
          ->initializeType($type);
        $this->negotiatedLanguages[$type] = reset($negotiation);
        $this->negotiatedMethods[$type] = key($negotiation);
        $this->initializing = FALSE;
      }
      elseif ($type == LanguageInterface::TYPE_INTERFACE) {
        return new Language([
          'id' => LanguageInterface::LANGCODE_SYSTEM,
        ]);
      }
    }
  }
  return $this->negotiatedLanguages[$type];
}

```

Then the result depends on the language negotiators you have configured in language detection, see comment from @Clive.

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


# Question
Title: How to get group ids by ids of elements of group content?
I use the Group module and I have created several groups and assigned several nodes as content of these groups.

For example, I know id of some node. How can I figure out which groups contain this node ? That is, how to get group ids by nid, if this node is a content of these groups ? And I don't want to use SQL for it. Are there methods of classes for it ?

# Answer
The way Group module maintainer recommended:

```
use Drupal\group\Entity\GroupContent;

function getGroupIdsByEntity($entity) {
  $group_ids = [];

  $group_contents = GroupContent::loadByEntity($entity);
  foreach ($group_contents as $group_content) {
    $group_ids[] = $group_content->getGroup()->id();
  }

  return $group_ids;
}

```
> 5 votes

# Answer
Try something like this: (gids will be your groups ids). I check the entity type because group content will also load the group members.

```
  $ids = \Drupal::entityQuery('group_content')
      ->condition('entity_id', $node->id())
      ->execute();

  $relations = \Drupal\group\Entity\GroupContent::loadMultiple($ids);

  foreach ($relations as $rel) {

    if ($rel->getEntity()->getEntityTypeId() == 'node') {

      $gids[] = $rel->getGroup()->id();
    }
  }

```
> 2 votes

# Answer
Another helpful function in this situation might be `getContentByEntityId($plugin_id, $id);` from `GroupInterface.php`. `$plugin_id` is the content enabler plugin ID to filter on and `$id` is your node id. However, you would need to loop through your groups and do `$groupContentArray = $group->getContentByEntityId($plugin_id, $id)` to get an array of GroupContentEntities (of your node) if they exist for this group.
> 0 votes

---
Tags: 8, group
---


# Question
Title: How can I invoke hook function after the block is loaded?
I have created a view with content types in my Drupal 8 and for this view page I have created a customised filter. The view page is located in sites/mysite/modules/view/config/install

And the customised filter is located in sites/mysite/modules/filter/src/Plugin/Block

The issue for me is that I want to change a title of the filter in hook function in view.module . But it is loaded before the FilterBlock. How can I specify the order of the invoked files?

# Answer
To change the order of which module's hook will fire first when more than one module implements the same hook you can use `hook_module_implements_alter()`. It was created for exactly this kind of situation.
> 1 votes

# Answer
There is two way to do so :

1. Using this module modules weight
2. Using hook\_module\_implements\_alter
> 1 votes

---
Tags: 8, hooks
---


# Question
Title: Drupal::config to access Site default timezone
Like the title says, I want to access the sites default timezone.

Guess

```
Drupal::config('system.date')->get('timezone')['default']

```

is the right function. I really would love to know how to use the config-function. Is there a list with all the configs, settings or variables that can be called?

Whats the logic behind the keywords "system.date"? Is there a way to discover keywords by looking at the yml config structure? Can all values of them be returned?

# Answer
> 2 votes
**Inspect the system.date configuration**

You can navigate to the */admin/config/development/configuration/single/export* path and inspect the configuration types and values. The *default timezone* is of type *simple configuration* and *system.date* is the *cofiguration name*.

**Inspect all the configuration values**

Go to */admin/config/development/configuration/full/export*, here you can export all the active configuration, you can download and extract the bundle and then inspect the individual files. If you have the *drush* command line tool, you could use the command `drush config:export`.

**Official Documentation**

You should read the official documentation to better understand the logic behind the *Configuration API*. These are some links:

Simple Configuration API | Drupal 8 guide on Drupal.org

Configuration API | Drupal 8 guide on Drupal.org

Configuration API overview | Drupal 8 guide on Drupal.org

---
Tags: 8, configuration
---


title: How to move Contextual Links?

text:
# Question
Title: How to move Contextual Links?
Added a wrapper inside a `block.tpl.php` called `block-content`:

```
<section id="<?php print $block_html_id; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
    <div class="block-content">

  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <h2<?php print $title_attributes; ?>><?php print $title; ?></h2>
  <?php endif;?>
  <?php print render($title_suffix); ?>

  <?php print $content ?>
    </div>

</section>

```

As you can see there is no sign of contextual links in it.

But if you look at the source, contextual links block is put inside the new `block-content`.

How to move contextual links block outside `block-content` one level up inside `section` so they both become children elements?

Goal is to separate block content wrapped in a separate container without contextual links because it interrupts a lot when it comes to CSS.

I got a solution with jQuery, but it's impractical on every page load for every block.

# Answer
you can create multiple tpl.php files for blocks based on the specific block, the module that created the block.

> Clone block.tpl.php to "block--block--\[block-id\].tpl.php" file

after try code, I don't' encourage you to do this, but it maybe the solution for you:

```
<section id="<?php print $block_html_id; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
    <div class="block-content">
      <?php print render($title_prefix); ?>
      <?php print render($title_suffix); ?>
      <?php if ($title): ?>
        <h2<?php print $title_attributes; ?>><?php print $title; ?></h2>
      <?php endif;?>
      <?php print $content ?>
    </div>
</section>

```

=\> Clear cache
> 1 votes

---
Tags: 7, theming, blocks, bootstrap-theme
---


title: hook_editor_js_settings_alter()

text:
# Question
Title: hook_editor_js_settings_alter()
I am using `hook_editor_js_settings_alter()` to disallow HTML tags in Ckeditor. It is only working in node edit form, and Ckeditor is in edit mode. Wen I preview the published page it allows the tags in my disallow custom hook.

The following code was a test to disallow `<h1>` tags with the class name *myHeader2*. If I change the class name to *myheader*, it work in edit mode and published mode. Is the class name the problem?

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\editor\Entity\Editor;

function mymodule_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as $name => $value) {
    $settings['editor']['formats']['rich_text']['editorSettings']['disallowedContent'] = 'h1(myHeader2)';
  }
}

```

# Answer
> 0 votes
Navigate to /admin/config/content/formats. For each text format, you can enable the *Limit allowed HTML tags and correct faulty HTML* filter, which is configurable with the *Allowed HTML tags* text box at the bottom of the configuration form.

This is how input formats are supposed to be changed.

---
Tags: 8, wysiwyg
---


# Question
Title: Where is the YAML file containing the user permissions stored?
Which directory contains the YAML file where user permissions per role are stored? I looked in the core.entity.yml and do not know where else to look.

# Answer
They are stored in the `user.role.ROLE_NAME.yml` files with the rest of configuration exports.
> 4 votes

---
Tags: 8
---


# Question
Title: Form element replaced via Ajax callback doesn't seem to be submitting or the values are not appearing in buildForm
I'm having a form with a select list and a textbox. On-change of select list will trigger an ajax callback. The callback function will replace the default value of textbox with an updated value. But when I try to get the textbox value in `buildForm()` or if I try to submit the form, instead of the updated value the default value (old value which is set) is passed on submit handler. Below is the code -

```
<?php

namespace Drupal\my_module\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\FormStateInterface;

class MyAjaxForm extends ConfigFormBase {

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

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

    $form['output'] = [
        '#type' => 'textfield',
        '#size' => '60',
        '#value' => 'oldvalue',
        '#default_value' => 'oldvalue',
        '#attributes' => [
            'id' => ['edit-output'],
        ],
    ];

    $form['input'] = array(
        '#title' => t('Crust Size'),
        '#type' => 'select',
        '#description' => 'Select the desired pizza crust size.',
        '#options' => [
          'medium' => 'Medium',
          'large' => 'large',
         ],
        '#ajax' => [
            'callback' => [$this, 'seyHello'],
            'event' => 'change',
            'wrapper' => 'edit-output',
            'progress' => [
                'type' => 'throbber',
                'message' => t('Verifying entry...'),
            ],
        ],
    );

    return parent::buildForm($form, $form_state);
    dpm($form['output']['#value']);
    //even after the ajax callback return and the textbox is filled with 'newvalue', dpm returns 'oldvalue' still.
  }

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

    dpm($form['output']['#value']);
    dpm($form_state->getValue('output'));
    //both returns 'oldvalue'

  }

  public function seyHello(array &$form, FormStateInterface &$form_state) : AjaxResponse {
    $elem = [
        '#type' => 'textfield',
        '#size' => '60',
        '#default_value' => 'newvalue',
        '#value' => 'newvalue',
        '#attributes' => [
            'id' => ['edit-output'],
        ],
    ];
    $renderer = \Drupal::service('renderer');
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#edit-output',
    $renderer->render($elem)));
    $form_state->setRebuild(TRUE);
    return $response;
  }

}

```

I'm not sure why this is happening, it clearly seems to be the case of form values not getting updated after the ajax callback for me. Been debugging this for entire day. Any help/ suggestions would be lovely. Thanks.

# Answer
The ajax callback returns the part of $form which is inside of the ajax wrapper:

```
  /**
   * Ajax callback for the color dropdown.
   */
  public function updateColor(array $form, FormStateInterface $form_state) {
    return $form['color_wrapper'];
  }

```

The wrapper has to be a div container.

Complete code example https://cgit.drupalcode.org/examples/tree/form\_api\_example/src/Form/AjaxColorForm.php
> 3 votes

---
Tags: 8, forms, ajax
---


# Question
Title: Is there a way to show a message to specific users?
I would like to programmatically set a message shown at least once for selected users or for all users with a specific role.

# Answer
Copy the following snippet to your module, then you have to replace ***MODULE*** with your ***module machine name***

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_preprocess_page(&$variables) {
  $message = t("You have been served!");
        $request = \Drupal::request();
  $session = $request->getSession();
  $message_was_displayed = $session->get('mymodule_message_was_displayed', FALSE);
  if ($message_was_displayed === FALSE) {
    $messenger = \Drupal::messenger();
    $messenger->addMessage($message);
    $session->set('mymodule_message_was_displayed', TRUE);
  }
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: Caption on CKEditor with Media embed only allows 128 characters
Using Drupal 8, the Media module, and the CKEditor that comes with D8. When you add an image media item, you get your screen like this...

But that caption field only allows 128 characters. Media (I believe) seems to be setting a maxlength of 128 (maxlength="128"). You can still add more characters if you Embed, then edit the source it supplies, but it's still going to chop off what you've added if you double click on that image (it's technically a drupal-entity element) to bring the "Embed media" window up again.

Since this "Caption" field is not dealing with any kind of data/database storage constraints, 1.) can I change this and 2.) does this even make any sense for it to have a maxlength set?

If anyone has a clue how to change it, that'd be most helpful.

# Answer
This should do the trick no need to install any module, substituting 500 with whatever you want the limit to be

```
 function mymodule_form_entity_embed_dialog_alter(&$form, $form_state, $form_id) {
      if(isset($form['attributes']['data-caption'])) {
        $form['attributes']['data-caption']['#maxlength'] = '500';
      }
    }

```
> 2 votes

# Answer
I ended up installing the maxlength module, and altering the form as such:

```
function mymodule_form_entity_embed_dialog_alter(&$form, $form_state, $form_id) {
  if(isset($form['attributes']['data-caption'])) {
    $form['attributes']['data-caption']['#maxlength'] = '524288';
    $form['attributes']['data-caption']['#maxlength_js'] = TRUE;
  }
}

```

Works great! It does create a dependency with the maxlength module, and puts the "limit" on the field (I went with what it said was the "default" of 524288), but other than that
> 0 votes

---
Tags: 8, media, wysiwyg
---


# Question
Title: How can I alter the value of a filter and have the output altered before the view renders?
When using Drupal 7 and Views 3, what is the correct way to alter a Views filter value so that it affects the content that's just about to be rendered?

I tried everything mentioned here for D6.

Even though a few people got it to work, Merlin states that modifying the display\_options is the incorrect way to achieve this, but he's vague in his response as to what to do (http://drupal.org/node/789710#comment-2927556).

I have tried:

```
function pages_views_pre_view($view){
    $view = views_get_view('north_carolina');
    $view->set_display('default');

    $view->display_handler->options['filters']['province']['value'] = 'Georgia';
    dsm($view->display_handler->options['filters']['province']);
}

```

Notes:

1) I have a view created called `north_carolina` that has two types of displays - a page and a block (page\_1 and block\_1).

2) my filters are the same across my displays so I am trying to change the 'default' display so that it affects all of them.

3) The default value of my filter is 'North Carolina' (which I set in the Views UI) but notice I am trying to change it to 'Georgia'

4) If I run DSM immediately after, I see that the filter has been changed, however, my results still show 'North Carolina' results. Caching is turned off, and I still get the same thing after running drush cc all.

I have also tried running that same code through `hook_views_pre_build` and `hook_views_pre_execute`.

Any suggestions?

EDIT:

As suggested it may help to have additional information. Here is a dump of the view:

```
$view = new view();
$view->name = 'north_carolina';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'North Carolina';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test nc block';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Location: Province */
$handler->display->display_options['filters']['province']['id'] = 'province';
$handler->display->display_options['filters']['province']['table'] = 'location';
$handler->display->display_options['filters']['province']['field'] = 'province';
$handler->display->display_options['filters']['province']['value'] = 'North Carolina';
$handler->display->display_options['filters']['province']['exposed'] = TRUE;
$handler->display->display_options['filters']['province']['expose']['operator_id'] = 'province_op';
$handler->display->display_options['filters']['province']['expose']['label'] = 'State';
$handler->display->display_options['filters']['province']['expose']['operator'] = 'province_op';
$handler->display->display_options['filters']['province']['expose']['identifier'] = 'province';
$handler->display->display_options['filters']['province']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->display->display_options['block_description'] = 'test nc block';

```

Note that these handlers are provided by the locations module. Specifically for the "Location: Province" filter I am given an auto complete form. When I type in North Carolina, it pops up, and I have to choose that. However, notice in the SQL statement that views generates it uses the two character abbreviation for state:

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM
{node} node
LEFT JOIN {location_instance} location_instance ON node.vid = location_instance.vid
LEFT JOIN {location} location ON location_instance.lid = location.lid
WHERE (( (node.status = '1') AND (location.province = 'NC') ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0

```

# Answer
It can be tough to figure out the exact part of the views object to modify. I usually export the view first and look at the generated code to get me started.

The snippet below is unmodified and working as expected on one of my production sites. Hopefully it's enough to get you headed in the right direction (obviously, this is in a custom module named `offer_select`). If you can provide the code from the exported view, someone might be able to take a look.

```
//Alter the End date filter on the offer views
function offer_select_views_pre_view(&$view) {
  if ($view->name == 'active_offers') {
    $view->display['default']->handler->options['filters']['field_end_value']['value']['value'] = time();
  }
}

```

--UPDATE--
For your specific view I installed the Location module and created a few nodes in NC and a few in Georgia and imported your view to test. In my custom module (named `dev`) I started with this code (with devel installed):

```
function dev_views_pre_view(&$view) {
  if ($view->name == 'north_carolina') {
    dpm($view->display['default']->handler->options['filters']);
  }
}

```

From there, I continued to add the obvious values displayed in krumo on to the array until I got here:

```
function dev_views_pre_view(&$view) {
  if ($view->name == 'north_carolina') {
    dpm($view->display['default']->handler->options['filters']['province']['value']);
  }
}

```

Which simply printed `North Carolina` in Krumo. At that point I changed from printing the value to setting it like this:

```
function dev_views_pre_view(&$view) {
  if ($view->name == 'north_carolina') {
    $view->display['default']->handler->options['filters']['province']['value'] = 'Georgia';
  }
}

```

And voila. That did the trick.
> 8 votes

# Answer
In case someone has this thread popped up while searching for same solution on D8 (as I did):

New API allows to manipulate these parameters in a lot more clear way. See this section for references.

Small example

```
function dev_views_pre_view(ViewExecutable &$view, $display_id, array &$args) {
  if ($display_id === 'my_unique_display_name') {
      $args[0] = 'desired_value';
  }
}

```
> 2 votes

---
Tags: views
---


# Question
Title: Custom block assigned to new region invalid
I had created a new region to my theme "buynow" and my theme.info contains the following line

```
regions[buynow] = Buynow

```

In my custom module i had created a custom block in which i assigned the block to the region buynow

```
function buynow_block_info() {
  $blocks = array();
  $blocks['buynow'] = array(
    'info' => t('Shoretel Buynow'),
    'status' => 1,
    'region' => 'buynow',
  );
  return $blocks;
}

```

When i try to enable the module, Iam getting **The block was assigned to the invalid region and the block was disabled**

How can i set my block to the new region.

# Answer
> 0 votes
You can use this code:

```
function formalter_block_info() {

 $blocks = array();

 $blocks['buynow'] = array(

 'info' => t('Shoretel Buynow'),

 'status' => 1, // This will enable your block by default, and set it to region given in 'region' option

 'region' => 'buynow', // put <machine-name of your region> in place of footer
 'visibility' => BLOCK_VISIBILITY_NOTLISTED,

 'weight' => 2,

 );
return $blocks;
}

```

# Answer
> 0 votes
Even though its an old issue I am pointing it to Drupal Discussion so others can benifit from it.

Here is the discussion regarding this in Drupal.org .

The problem occurs when the assigned region is not present in default themes.When we assign a region to a block through custom module it is assigned to all the available themes not just current active theme.

For example Seven is the administator theme in Drupal 7 , it has only 4 regions but default theme Bartik has more then 4 regions so if if you assign a region which is present in Bartik theme to block through custom module it cant get assigned to the same region in Seven theme as it is not present, hence the Warning will be thrown.

---
Tags: blocks, theming
---


title: Hide a row from view display

text:
# Question
Title: Hide a row from view display
I have a view which presents values of specific content type, nothing special, just a normal regular view with a table display. Later on I added to it a field from *views field view* module. Everythink works as expected. Now I need to hide every row which has an empty value of this *views field view* field?

Any ideas how can I do it?

I tried to use *hook\_views\_pre\_render* but in this case I can only get an access to values of fields from parent view not from the one which comes from *views field view*.

Any help will be appreciated!

P.S. The question applies to Drupal 8

# Answer
> 2 votes
You can do it in a preprocess template function.
e.g.

```
/**
 * Implements template_preprocess_views_view_table()
 * @param $variables
 */
function TEMPLATE_preprocess_views_view_table(&$variables){
  /** @var ViewExecutable $view */
  $view = $variables['view'];

  //Do no alter other views
  if ($view->id() !== 'YOUR_VIEW_ID') return;

  $rows = $variables['rows'];
  foreach ($rows as $key => $row){
    if (empty($row['columns']['VIEWS_FIELD_VIEW_FIELD_NAME']['content'])){
      unset($variables['rows'][$key]);
    }
  }
}

```

Replace
TEMPLATE with your module name or theme name. YOUR\_VIEW\_ID with your view id VIEWS\_FIELD\_VIEW\_FIELD\_NAME with the name of your field

Hope that helps

# Answer
> 1 votes
Are you passing argument to the view embed? If true, you should apply the hide field if that argument is empty, so you don't need to control the row on the new view.

---
Tags: views, 8, hooks
---


# Question
Title: How to right-to-left emails are right-aligned?
In my Drupal 8 site, I am using Arabic email for sign up, log in, forgot password. I get Arabic email content, however, the email content is left aligned. I am using PHP Mailer on my site for sending emails. When I tried with Mail Systems + Mime Mail + SMTP, then I get an error like "reply-to" is not set. Is it possible to align Arabic email content from right to left using PHPMailer?

# Answer
You can install Mime Mail or HTML Mail module to enable HTML emails in your Drupal instance.
Then, through configuration translation, you can add `dir="rtl"` to the container enclosing your Arabic email message.
> 0 votes

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


# Question
Title: How can I POST x-www-form-urlencoded data from REST API plugin?
In Drupal 8, the REST API plugin can have a serialization format, such as `xml` or `json`. This affects the accepted "request formats" for a resource.

Is it possible to add a format for `application/x-www-form-urlencoded` handling for the REST plugin? or does this need to be handled in a form controller instead?

# Answer
> 3 votes
While looking into this, I found this solution to accept form encoded POST data and respond with JSON:

```
<?php

namespace Drupal\example\Encoder;

use Drupal\serialization\Encoder\JsonEncoder as SerializationJsonEncoder;

/**
 * Decodes form data and returns JSON.
 *
 * Simply respond to form format requests using the JSON encoder.
 */
class FormJsonEncoder extends SerializationJsonEncoder {

  /**
   * The formats that this Encoder supports.
   *
   * @var string
   */
  protected static $format = ['form'];

  /**
   * {@inheritdoc}
   */
  public function decode($data, $format, array $context = array()) {
    parse_str($data, $result);
    return $result;
  }

}

```

and then add the encoder to the `example.services.yml`

```
services:
  serializer.encoder.form:
    class: Drupal\example\Encoder\FormJsonEncoder
    tags:
      - { name: encoder, format: form }

```

After that, the "Accepted request format" can be selected on the rest plugin config page:

*admin/config/services/rest/resource/example\_rest\_plugin/edit*

---
Tags: 8, plugins
---


title: Get current node id from controller

text:
# Question
Title: Get current node id from controller
I am building a module with reactjs and I need to get the current node id from a controller so I can do certain tasks based on the node id but I always receive a null value, my routing is working correctly and my function is the following:

```
  public function currentNodeId()
    {
        // get current node
        $node_id = \Drupal::routeMatch()->getParameter('node')->Id();

        return new JsonResponse(
            array(
                'node_id' => $node_id
            )
        );
    }

```

and in mymodule.routing.yml I have:

```
 mymodule-currentNode:
   path: '/mymodule/currentNodeId'
   defaults:
     _controller: '\Drupal\mymodule\Controller\MyModuleController::currentNodeId'
     _title: 'Current node id'
   requirements:
     _permission: 'access content'

```

I can get the current node id from my module file 'mymodule.module' doing the same I did in the currentNodeId function:

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

```

Anyone knows if this is some kind of security or am I doing anything wrong? Thank you

EDIT

This is what I have in my js file, I do this call and I want to get the current node id so then I can do a certain task, in the console I get null or undefined every time I do the request

```
$.get('/mymodule/currentNodeId/', function (data) {
                        console.log(data.node_id);
                    });

```

# Answer
Your route has no node parameter. See the documentation Structure of routes and the example from there:

```
book.export:
  # This path takes dynamic arguments, which are enclosed in { }.
  path: '/book/export/{type}/{node}'
  defaults:
    # Because this route does not return HTML, use _controller.
    _controller: '\Drupal\book\Controller\BookController::bookExport'
  requirements:
    _permission: 'access printer-friendly version'
    # Ensure user has access to view the node passed in.
    _entity_access: 'node.view'

```

You can access the route parameters in the controller directly in the function arguments:

```
public function bookExport($type, NodeInterface $node) {
  // get the id from the controller argument
  $node_id = $node->id();
}

```

`\Drupal::routeMatch()->getParameter()` is to get a route parameter outside of the controller, for example in a preprocess hook. For this to work the parameter has to be defined in the current route as well.
> 1 votes

# Answer
I just wrote a blog article about a dynamic Drupal 8 alternative on https://julian.pustkuchen.com/node/780

Here's my code for a helper function:

```
<?php
/**
 * Helper function to return the currently loaded entity from the URL (controller).
 * Returns NULL if the currently loaded page is no entity.
 *
 * @return \Drupal\Core\Entity\EntityInterface
 */
function _get_current_controller_entity()
{
  $currentRouteParameters = \Drupal::routeMatch()->getParameters();
  foreach ($currentRouteParameters as $param) {
    if ($param instanceof \Drupal\Core\Entity\EntityInterface) {
      $entity = $param;
      return $entity;
    }
  }
  return NULL;
}
?>

```

Handle and test with care. We're using it for different types of content entities like nodes, users, commerce\_products, ... so far.
> 1 votes

---
Tags: 8, nodes
---


title: Batch API: What am I doing wrong?

text:
# Question
Title: Batch API: What am I doing wrong?
I am trying to import some videos into a 8.0.5 site (yes, I know I should upgrade) I have over 200 videos that neeed to be imported into their own individual node. It seems like a perfect opportunity to get my head around the batch api.

After getting all the videos as objects in a sigle array, I then chunk this into batches of 10 using array\_chunk() and then set each chunk as its own opperation.

I would have thought that the batch api would have sent each data array as a signle array to my process function. However, it seems that only the first video from each batch is getting processed.

If I add the &$context variable to my process function and dump it out, it just shows me the next object.

Please, can anyone point out what I have done wrong? :(

```
public function batchStart() {

ini_set('max_execution_time', 0);
$directory = drupal_get_path('module', 'drp_broadcast_videos_importer') . '/broadcast-videos';
$videoImporter = new VideoImporterController();
$videosArray = $videoImporter->getVideosFromDirectory($directory);
// Chunk up the array.
$videoChunks = array_chunk($videosArray, 5);

foreach ($videoChunks as $chunk) {
  $operations[] = [
    '\Drupal\drp_broadcast_videos_importer\Controller\ImportController::processBatch',
    $chunk,
  ];
}

$batch = [
  'title' => t('Processing Batch'),
  'operations' => $operations,
  'finished' => '\Drupal\drp_broadcast_videos_importer\Controller\ImportController::finishedBatch',
  'init_message' => t('Batch is starting.'),
  'progress_message' => t('Processed @current out of @total.'),
  'error_message' => t('Batch has encountered an error.'),
];

batch_set($batch);

return batch_process('/');
}

static function processBatch($video, $context) {
  try {
    $file = (new VideoImporterController())->createNewFileEntity($video->video, $video->filename);

    $broadcastNode = Node::create(['type' => 'broadcast_video']);
    $broadcastNode->setTitle($video->title);
    $broadcastNode->setOwnerId(\Drupal::currentUser()->id());
    $broadcastNode->setCreatedTime($video->date);
    $broadcastNode->set('field_broadcast_pack_name', $video->pack);
    $broadcastNode->set('field_videos', ['target_id' => $file->id()]);
    $broadcastNode->save();

    $context['message'] = $video->title . ' processed.';
    $context['results'][] = $video->id;

  }
  catch (EntityStorageException $exception) {
//              \Drupal::logger('broadcast_videos_importer')
 //                ->error($this
//                  ->t(
//                    'The broadcast video @title could not be uploaded',
//                    ["@title" => $videoObject->title]
//                  )
//                );
//              drupal_set_message($this->t(
//                'The broadcast video @title could not be uploaded',
//                ["@title" => $videoObject->title]));
    }
  return $broadcastNode->id();
 }

```

# Answer
```
$operations[] = [
  '\Drupal\drp_broadcast_videos_importer\Controller\ImportController::processBatch',
  $chunk,
];

```

In the above, `$chunk` is the list of parameters that will be passed to the batch process method. So if `$chunk` is an array of 5 videos, your method signature would need to look like this to match.

```
static function processBatch($video1, $video2, $video3, $video4, $video5, &$context) {

```

That's probably not what you're hoping for. To fix, just wrap `$chunk` in array:

```
$operations[] = [
  '\Drupal\drp_broadcast_videos_importer\Controller\ImportController::processBatch',
  [$chunk],
];

```

Now your process method signature looks like this:

```
static function processBatch($videos, &$context) {

```

And you just need to loop through the videos in each operation.
> 3 votes

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


# Question
Title: Why does JavaScript attached in a widgets render array return the variable value from only the first widget added
I have a custom field type called signature\_field. It invokes a JS file and has its own custom template. I pass a variable to both the JS file and template called $text\_area\_id. In Drupal if I add multiple fields on the same node with my custom signature\_field type my variable is correctly passed to the template for each of the various fields. The JavaScriot code, however, returns only the ID fo the first field added for each of the subsequent fields.

I pass `$text_area_id` using the following code from the SignatureWidget.php file of a custom module to both the JavaScript code and the template.

```
namespace Drupal\signature_field\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\ElementInfoManagerInterface;

/**
 * Plugin implementation of the 'field_signature_field_widget' widget.
 *
 * @FieldWidget(
 *   id = "field_signature_field_widget",
 *   module = "signature_field",
 *   label = @Translation("Signature Data"),
 *   field_types = {
 *     "field_signature"
 *   }
 * )
 */
class SignatureWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

     //
     //$sign_thumb = array( '#type'   => 'html_tag',
     //                     '#tag' => 'img',
     //                     '#attributes' => array('src' => '', 'id' => 'signature_thumb_test', 'class'=>array('align-right'), 'width' =>'120px', 'height' => '60px' ));

    $field_name = $items->getName();

    /*function getFieldName() {
      return $field_name;
    }*/

    $text_area_id = 'signature_field_' . $field_name;

    $file_upload_help = array(
      '#theme' => 'signature',
      '#sign_src' => $value,
      '#text_area_id' => $text_area_id,
    );

    $element += array(
      '#type' => 'textarea',
      '#default_value' => $value,
      '#attributes' => array(
        'id' => array($text_area_id),
                        ),
      '#attached' => array(
        'library' => array('signature_field/signature_pad'),
                        ),
    );
    $element['#attached']['library'][] = 'signature_field/signature_pad';
    $element['#description'] = \Drupal::service('renderer')->renderPlain($file_upload_help);
    $element['#attached']['drupalSettings']['signature_field']['sign']['id'] = $text_area_id;

    return array('value' => $element);
  }

}

```

The template code is the following one.

```
<div class="signature">
    <p>{{text_area_id}}</p>
    <canvas width="450" height="200" id="{{text_area_id}}_canvas" class="sign-canvas">SIGNATURE CANVAS</canvas>
{% if(sign_src != '') %}
    <img src = {{sign_src}} id="{{text_area_id}}_image" class="sign-img"></img>
{% endif %}
     <button type="button" id="{{text_area_id}}_clear_sign" class="button clear" data-action="clear">Clear</button>
</div>

```

It correctly returns different values based on the field name for each of the fields on the given node. The JavaScript code is the following.

```
(function ($, window, Drupal, drupalSettings) {

    Drupal.behaviors.signature = {
        attach: function (context, settings) {

            var canvasId = drupalSettings.signature_field.sign.id;
            console.log(canvasId);

            var canvas = document.querySelector('#' + canvasId + "_canvas");
            var signaturePad = new SignaturePad(canvas, {
                minWidth: 0.5,
                maxWidth: 2.5,
                backgroundColor: "rgb(250, 250, 250)",
                penColor: "rgb(66, 133, 244)",
                onEnd:function(){
                    $('#' + canvasId).val(signaturePad.toDataURL());
                }
            });

            $('#' + canvasId).hide();
            $('#' + canvasId + '_clear_sign').click(function(){
                var signaturePad;
                var canvas = document.querySelector('#' + canvasId + "_canvas");
                signaturePad = new SignaturePad(canvas,{
                 penColor: "rgb(66, 133, 244)",
                });
                signaturePad.clear();
                $('#' + canvasId).val('');
            });
            if ($('#' + canvasId + "_image").attr('src')) {
                $('#' + canvasId + "_canvas").hide();
                $('#' + canvasId + '_clear_sign').addClass('chnge-canvas');
            }
            if ($('#' + canvasId + '_clear_sign' + '.chnge-canvas').length) {
                $('#' + canvasId + '_clear_sign' + '.chnge-canvas').click(function(){
                    $('#' + canvasId + '_clear_sign').removeClass('chnge-canvas');
                    $('#' + canvasId + "_image").hide().attr({ 'src':''});
                    $('#' + canvasId + "_canvas").show();
                });
            }

        },
        detach: function (context) {

        }
    };

})(jQuery, this, Drupal, drupalSettings);

```

The console log -

```
var canvasId = drupalSettings.signature_field.sign.id;
                console.log(canvasId);

```

It returns the field name for only the first value of the widget added from the node. It returns it multiple times based on how many times the custom field\_type is invoked. How can I get the id for each of the fields in JavaScript? Why does this work different in the template and the JavaScript code?

# Answer
As @Berdir stated, the values are overwritten because the drupalSettings object is merged and your JS file is actually loaded once.
You should pass the IDS as array e.g.:

```
$element['#attached']['drupalSettings']['signature_field']['sign'][] = $text_area_id;

```

Then your JS, in the attach function you should loop through them and add the functionality separately, e.g.:

```
(function ($, window, Drupal, drupalSettings) {

    Drupal.behaviors.signature = {
        attach: function (context, settings) {

            var canvasIds = drupalSettings.signature_field.sign;
            for (var i=0, length = canvasIds.length; i < length; i++){
              this.initiateCanvas(canvasIds[i])
            }
        },
        initiateCanvas: function(canvasId){
          console.log(canvasId); // Yeilds the first id 4 times
          var canvas = document.querySelector('#' + canvasId + "_canvas");
          var signaturePad = new SignaturePad(canvas, {
              minWidth: 0.5,
              maxWidth: 2.5,
              backgroundColor: "rgb(250, 250, 250)",
              penColor: "rgb(66, 133, 244)",
              onEnd:function(){
                  $('#' + canvasId).val(signaturePad.toDataURL());
              }
          });

          $('#' + canvasId).hide();
          $('#' + canvasId + '_clear_sign').click(function(){
              var signaturePad;
              var canvas = document.querySelector('#' + canvasId + "_canvas");
              signaturePad = new SignaturePad(canvas,{
               penColor: "rgb(66, 133, 244)",
              });
              signaturePad.clear();
              $('#' + canvasId).val('');
          });
          if ($('#' + canvasId + "_image").attr('src')) {
              $('#' + canvasId + "_canvas").hide();
              $('#' + canvasId + '_clear_sign').addClass('chnge-canvas');
          }
          if ($('#' + canvasId + '_clear_sign' + '.chnge-canvas').length) {
              $('#' + canvasId + '_clear_sign' + '.chnge-canvas').click(function(){
                  $('#' + canvasId + '_clear_sign').removeClass('chnge-canvas');
                  $('#' + canvasId + "_image").hide().attr({ 'src':''});
                  $('#' + canvasId + "_canvas").show();
              });
          }
        },
        detach: function (context) {

        }
    };

})(jQuery, this, Drupal, drupalSettings);

```

UPDATE: Ok, I found the issue. We were trying to attached the settings to the $element, it should be attached to the $form, like this:

```
$form['#attached']['drupalSettings']['signature_field']['sign'][] = $text_area_id;

```

I tested this and it is working!
> 2 votes

# Answer
Not very familiar with 8 yet, but with 7, the field where the JS is attached should be stored under the context.
> -2 votes

---
Tags: 8, javascript
---


# Question
Title: Reply form not showing for ajax_comment module installed for Open social distribution
recently I've installed Open Social Distribution and installed the ajax\_comment module to enable ajax comments and reply but unfortunately the reply link never appear at the home page that shows all posts here is a screenshot of a post showing in home page:

# Answer
Make Sure that connected user has `Post comments` Permission Or anonymous has it.
> 0 votes

---
Tags: 8
---


# Question
Title: After Update to 8.5.6, "Add" Links Missing From Page but still are in router
I recently **manually** updated Drupal to the 8.5.6 version. I did this by moveing over the files (using command line) according to Drupal.org instructions and running update.php.

I have two issues that I'm guessing are related:

1. My themes no longer toggle from the front end and I can't force them to change by clearing cache, running cron, rebuilding menu or anything else that I can think of.
2. All "add" links are missing \** - "Node/add" is present in the routing file and still works. However, it is missing from the content page. It also seems that ALL "add" links are missing from the site. To get there, I need to manually type in the path.

I am running out of obvious ideas on how to fix. Can anyone point me in the right direction?

**I followed the instructions below:**

Drupal Page on Running Installation Manually

Below, you can see the commands Drupal tells you to follow:

```
cd /path/to/your/drupal/directory
rm -rf core vendor
rm -f *.* .[a-z]*
wget https://www.drupal.org/files/projects/drupal-x.y.z.tar.gz
tar -zxvf drupal-x.y.z.tar.gz
cd drupal-x.y.z
cp -R core vendor /path/to/your/drupal/directory
cp *.* .[a-z]* /path/to/your/drupal/directory

```

# Answer
Thank you everyone for your feedback.

We ended up wiping the whole server and starting over. I had done various updates manually by dragging and dropping. We re-installed Drupal and this time around used composer and drush. That solved the issue. I was not able to ever FINALLY diagnose what happened.
> 0 votes

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


title: Cannot Uninstall Purchased Theme, Porto

text:
# Question
Title: Cannot Uninstall Purchased Theme, Porto
I purchased a theme called "Porto" which is quite good. With that said, for troubleshooting purposes, I need to turn that theme off.

I can uninstall every theme on the site **except** "seven" and this purchased theme.

When we installed the theme, we had to do a whole install using SQL rather than just dragging over the theme file. I BELIEVE that there is something in these files that is preventing them from being uninstalled but I'm not sure where to look.

Can someone tell me where I might look to find this setting and override it? In the theme file? Setting file?

# Answer
> 3 votes
You can't uninstall the default theme, because there wouldn't be a theme left for the site. Similarly you can't uninstall the Seven theme when it's selected as the admin theme.

You need to change the default to another theme, then under normal circumstances the "Uninstall" link will appear where you'd expect it.

If it doesn't, consult the documentation or contact support for the theme seller, because they've done something non-standard, and it's not likely to be possible to guess what that might have been from afar (especially if it was done as part of the initial SQL import)

---
Tags: theming
---


title: Why wrap lines in plain emails?

text:
# Question
Title: Why wrap lines in plain emails?
Drupal adds line breaks after a width of 77 in the function *wrapMailLine()* of the class *core/lib/Drupal/Core/Mail/MailFormatHelper.php*.

What is the reason for that?

If you open the mail in a small viewport like on a phone, e.g. the line breaks after 50 chars and then again after 27 chars. This behavior is undesired.

# Answer
> 0 votes
Because of RFC2822 (Internet Message Format), section 2.1.1 (Line Length Limits):

> There are two limits that this standard places on the number of characters in a line. Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF.

Why they chose 77 and not 78 for Drupal, I don't know, but I'd bet my house the decision was originally based on that standard.

---
Tags: emails
---


# Question
Title: How do I programmatically check whether a custom entity is stored in external database?
In Drupal 8, how do I programmatically check whether a custom entity is stored in the external database using the entity ID?

Do we have any method/service to check whether a custom entity is stored in an external database using the entity ID?

# Answer
> 0 votes
Presuming you have configured the external database correctly inside `settings.php` you have to use `db_set_active('MYEXTERNALDATABASE')`, then do your DB query to check for your ID and when you're done `db_set_active('default')` set the active database back.

`db_set_active`

> Sets a new active database.

---
Tags: database
---


# Question
Title: Node "add" with already set paragraph fields
Each of my article nodes has a set of 7 paragraphs elements that must be filled in. Is there some way the client does not have to add them manually each time?

Would I create a hook that adds some kind of auto (default) paragraph entity to the paragraph field when the node is created?

Is this technically possible?

I think I have seen once a module that allows to define default paragraphs via the url.

But I think I am wrong.

# Answer
Actually it is pretty simple. I have written a module with the following hook:

Hope that helps somebody. Pretty handy and user friendly when it comes to content that is mainly created through paragraphs elements.

You attach the field widgets to the node when the add form is opened.

```
function xxx_entity_prepare_form(EntityInterface $entity, $operation, FormStateInterface $form_state) {

    if("article" === $entity->bundle()){
        $bundles = ['article_navigation_banner', 'call_to_action_banner', 'author_information'];
        $entity_manager = \Drupal::entityManager();
        $langcode = $form_state->get('langcode');

        $field = $entity->get('field_ui_elements');

        $target_type = $field->getSetting('target_type');

        foreach ($bundles as $bundle_name) {
            // Create paragraph and display.
            $entity_type = $entity_manager->getDefinition($target_type);
            $bundle_key = $entity_type->getKey('bundle');

            $options = array(
                $bundle_key => $bundle_name,
                'langcode' => $langcode,
            );

            if("call_to_action_banner" === $bundle_name){

            }

            /** @var FieldableEntityInterface $paragraphs_entity */
            $paragraphs_entity = $entity_manager->getStorage($target_type)->create($options);

            // Field values.
            $field->appendItem($paragraphs_entity);
        }

    }

}

```
> 1 votes

---
Tags: 8, nodes, paragraphs
---


# Question
Title: Add a new field collection item to an existing field collection
I have 1 field collection

Field collection: CKT Info child2
machine name: field\_ckt\_info\_child2

In that have 2 fields:

Field1: English CKT child2
machine name: field\_eng

Field2: Maths CKT Child2
Machine name: field\_maths\_ckt\_child2

I have set field setting "unlimited" to this field collection. Now I just want to add new field collection item in existing Field collection(CKT Info child2) programmatically. I have tried below code but it's not creating new field collection item.

```
function createFC()  {
   $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_maths_ckt_child2'));
   $field_collection_item->setHostEntity($node);
   $field_collection_item->set('field_maths_ckt_child2', "SET SUCCESS");
   $field_collection->save();
}

```

# Answer
You can try code:

```
<?php

use Drupal\field_collection\Entity\FieldCollectionItem;
use Drupal\node\Entity\Node;

[....]

$node = Node::load(1);

$field_collection_items = $node->field_ckt_info_child2;
$fieldCollectionList = $field_collection_items;
if (count($fieldCollectionList)) {
 //update
  $field_collection_item = FieldCollectionItem::load($fieldCollectionList[0]->value);
}
else {
  //create new fieldconlection
  $field_collection_item = FieldCollectionItem::create(
    [
      'field_name' => 'field_ckt_info_child2',
    ]
  );
  $field_collection_item->setHostEntity($node);
  $field_collection_item->set('field_eng', 'HELLO');
  $field_collection_item->set('field_maths_ckt_child2', 'WORLD');
  $node->field_ckt_info_child2[] = ['field_collection_item' => $field_collection_item];
}

$node->save();

```
> 2 votes

---
Tags: 8, entities
---


# Question
Title: How to set the file status of files uploaded through theme settings to permanent?
I have been trying for a week to get image files uploaded to a Drupal server through the use of "managed\_file" theme settings to remain on the site longer than the default 6 hours. I have visited the Stack Overflow/Exchange forums before (https://stackoverflow.com/questions/8793518/set-file-status-permanent-for-appearance-settings-file-upload) (Uploaded images in theme settings is going to be lost) and have done my best to implement the provided solutions, but the uploaded files always disappear after 6 hours.

Here is one of the managed\_file fields which I wish to make permanent:

```
$form['mentor_settings']['global_settings']['header_settings']['header_background_image'] = array(
      '#type' => 'managed_file',
      '#title' => t('Header Background Image'),
      '#default_value' => theme_get_setting('header_background_image'),
      '#description' => t('This image will match the full dimensions of the header in the back.'),
      '#upload_location' => 'public://themesettingspictures',
      '#upload_validators' => array(
        'file_validate_extensions' => array("png jpg jpeg gif"),
             ),
  );

```

The file is properly moved to the specified folder. I have attempted to set the file status to permanent using the code provided in the above links, but it has never worked.

I would like to know if anyone can show me what function will set the file status for me AND can show me how to write it for the setting above, with its very long array "path". The examples I have tried to imitate have always been for 1st level theme settings, but my theme has three different levels of settings, so I'm never sure if I'm referencing my individual settings properly when trying to change file status.

One more note: I have been a self-taught front end Wordpress and Drupal web designer for a year now, but my knowledge of PHP is weak and so I am usually unable to code and back-end functions on my own. If you simply tell me to "use" a certain PHP function, I will have no idea how to apply it within the context of Drupal. If you respond to my post with references to PHP functions, please explain if they must be in a certain file (theme-setting.php vs template.php) and provide any other Drupal contextual information.

# Answer
You need set status `FILE_STATUS_PERMANENT` file when form submit

```
function mymodule_custom_form_submit($form, &$form_state) {
  if (isset($form_state['values']['images'])) {
    $file = file_load($form_state['values']['images']);

    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);
  }
}

```
> 2 votes

# Answer
Drupal deletes on cron runs any files that are not in usage. So basically only files in file or e.g. image fields will remain in the system.

But there is a module for that:

https://www.drupal.org/project/file\_lock

All newly uploaded files will be in usage by the file lock module than.
> 1 votes

---
Tags: 7, files
---


title: Recreate admin user

text:
# Question
Title: Recreate admin user
My login to Drupal 8 instance has failed. ive had a look in the DB and in the users table are 3 entries i dont recognise and the admin username (say 'adminuser') ive been using for the last year (but not accessed for several months) isnt there.

Ive contacted the hosting Co - they can backup the whole DB to a time when 'adminuser' existed but i could lose some data . Not too helpful about sorting out what has happened and when though.

Ive got cpanel access . can I recreate my adminuser through phypmyadmin ? '

# Answer
> -2 votes
Yes...

But know. The password field has been hashed.

Now their are a few ways to get the correct hashed value to manually add the updated/correct info. For example:

You can use a basic install on a localhost for example to create the user and export that table's content. On your live server via myphpadmin delete the user entery that has UID 1 and import the contents you exported. It will replace the username and password for you to be able to login.

---
Tags: 8, database
---


# Question
Title: What is the correct way to exclude certain CSS files for anonymous, but include for authenticated users?
We have a subtheme, `mytheme` that is based off of the `classy` base theme. We have set `Aggregate CSS Files = true` and when the pages load we end up with many aggregated CSS files.

One issue is that we don't need all the CSS for anonymous users, only authenticated users since most of them are for logged in users.

How would I only add the following CSS for only authenticated users, but not anonymous users using the `mytheme.libraries.yml`?

Goal:

* We do not want to override anything in those libraries, but rather remove them all together from render based on if the user is authenticated or not.

CSS files included in local development:

```
<styles media="all">
@import url("/core/themes/classy/css/components/progress.css?pe4tq3");
@import url("/core/themes/classy/css/components/dialog.css?pe4tq3");
@import url("/core/themes/classy/css/components/action-links.css?pe4tq3");
@import url("/core/themes/classy/css/components/button.css?pe4tq3");
@import url("/core/themes/classy/css/components/collapse-processed.css?pe4tq3");
@import url("/core/themes/classy/css/components/container-inline.css?pe4tq3");
@import url("/core/themes/classy/css/components/details.css?pe4tq3");
@import url("/core/themes/classy/css/components/exposed-filters.css?pe4tq3");
@import url("/core/themes/classy/css/components/field.css?pe4tq3");
@import url("/core/themes/classy/css/components/form.css?pe4tq3");
@import url("/core/themes/classy/css/components/icons.css?pe4tq3");
@import url("/core/themes/classy/css/components/inline-form.css?pe4tq3");
@import url("/core/themes/classy/css/components/item-list.css?pe4tq3");
@import url("/core/themes/classy/css/components/link.css?pe4tq3");
@import url("/core/themes/classy/css/components/links.css?pe4tq3");
@import url("/core/themes/classy/css/components/more-link.css?pe4tq3");
@import url("/core/themes/classy/css/components/pager.css?pe4tq3");
@import url("/core/themes/classy/css/components/tabledrag.css?pe4tq3");
@import url("/core/themes/classy/css/components/tableselect.css?pe4tq3");
@import url("/core/themes/classy/css/components/tablesort.css?pe4tq3");
@import url("/core/themes/classy/css/components/textarea.css?pe4tq3");
@import url("/core/themes/classy/css/components/ui-dialog.css?pe4tq3");
@import url("/core/themes/classy/css/components/messages.css?pe4tq3");
</styles>

```

We initially thought to do the following in the `mytheme.info.yml` file, but that would mean we have to exclude every single CSS manually (line by line).

```
name: 'mytheme'
type: theme
base theme: classy
package: custom
core: 8.x
libraries:
  - mytheme/library1
stylesheets-remove:
  - core/assets/vendor/normalize-css/normalize.css

```

# Answer
> 1 votes
You should use `hook_library_info_alter`.

In which, you check is the user is logged in, or the logged in user roles, then simply unset the CSS files you don't want.

# Answer
> 1 votes
Alternatively, instead of excluding select css files, you can use a progressive approach, loading stylesheets as needed. To do so:

1. Create a second stylesheet library \[suppose you call it *authenticated-styles*\] for authenticated users in your theme.libraries.yml file that represents all the css only authenticated users should see.
2. Then update your global theme library to only include the css for non-authenticated users.
3. Then, you can use the `hook_page_attachments_alter` function to detect if the user is logged in and attach the library using:

---

```
function MYTHEME/MYMODULE_page_attachments_alter(array $attachments) {

  $userCurrent = \Drupal::currentUser();

  if ($userCurrent->isAuthenticated()) {

    $attachments['#attached']['library'][] = 'mytheme/authenticated-styles'
  }

  return $attachments;
}

```

---
Tags: 8, css-js-aggregation
---


# Question
Title: Use multiple email addresses on contact form
I'm using the default D7 contact form to have anonymous users enter some information. I've created various categories and based on the category the message should be emailed to a single or multiple email addresses. The email addresses are valid addresses comma separated as described by D7.

This has worked fine for many years but recently emails are refused by Google due to multiple addresses in the From: header. So D7 sends the content of the contact form to both email addresses but also to the email address entered but with the entire list of email addresses in the From: header.

Is there a way to have both? i.e.

* copy of the message sent to the user, with a single, preset email address
* message sent to a list of email addresses based on the category.

Preferably with the standard contact form or with a separate module.

# Answer
> 2 votes
Despite being an old post, I think it warrants an answer for those sites still operating on Drupal 7 or even Drupal 8. Rather than use the built-in Contact form, I recommend using the Webform module. Below is a description of how it can be used for a contact form of this nature, with Drupal 7 specific screenshots.

If you setup your contact form using the Webform module, you can setup distinct emails, one for each purpose. In both cases, the "from" setting can be set to one unique site email address, a preset/predefined email address in the configuration, or one email address from the form itself.

---
Tags: emails
---