# Question
Title: Creating products with Rules and calculating price in Drupal Commerce
I am creating products on the fly with Rules, using Drupal Commerce. After user clicks on checkbox near product (additional service to product), I need to "add the service" to cart. Service is always 15% of price of Base product.

I created a rule which creates new products, and add them to cart. This works nicely but I am unable to set up the price field. In Data Selector mode I can not see my calculation field anywhere, not even when calculated value is Integer and price is also integer.

Any help with this? I am posting a Rule here:

```
{ "rules_grafeon_doplnkov_slu_by_pri_pridan_do_kosika" : {
"LABEL" : "Grafeon - Doplnkov\u00e9 slu\u017eby pri pridan\u00ed do ko\u0161\u00edka",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_discount_extra", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "commerce-line-item" ],
      "field" : "field_doplnkove_sluzby_item"
    }
  },
  { "data_is" : {
      "data" : [ "commerce-line-item:field-doplnkove-sluzby-item:0" ],
      "value" : "Service SLA"
    }
  },
  { "commerce_discount_extra_line_item_has_product_type" : {
      "commerce_line_item" : [ "commerce_line_item" ],
      "product_types" : { "value" : { "product" : "product" } }
    }
  }
],
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "date", "value" : "now" },
      "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
    }
  },
  { "data_convert" : {
      "USING" : { "type" : "text", "value" : [ "variable-added" ] },
      "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
    }
  },
  { "entity_query" : {
      "USING" : {
        "type" : "commerce_order",
        "property" : "order_id",
        "value" : [ "commerce-line-item:order-id" ]
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "entity_create" : {
      "USING" : {
        "type" : "commerce_product",
        "param_sku" : "DS-[commerce-line-item:order-id]-[conversion-result:value]",
        "param_type" : "doplnkov_slu_by",
        "param_title" : "Service SLA",
        "param_creator" : [ "site:current-user" ],
        "param_commerce_price" : { "value" : { "amount" : 1000, "currency_code" : "EUR" } },
        "param_commerce_stock" : "1000"
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
  { "commerce_cart_product_add_by_sku" : {
      "USING" : {
        "user" : [ "site:current-user" ],
        "sku" : "DS-[commerce-line-item:order-id]-[conversion-result:value]",
        "quantity" : "1",
        "combine" : "0"
      },
      "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
    }
  }
]

```

} }

Any advice how to get the value to Price value? Thanks a lot.

# Answer
> 0 votes
Well It looks like I found a way. I needed to save an entity before adding to cart.

If someone will found himself struggling in the same spot, I will leave an exported rule here:

```
{ "rules_grafeon_doplnkov_slu_by_pri_pridan_do_kosika" : {
    "LABEL" : "Grafeon - Doplnkov\u00e9 slu\u017eby pri pridan\u00ed do ko\u0161\u00edka",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_discount_extra", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item" ],
          "field" : "field_doplnkove_sluzby_item"
        }
      },
      { "data_is" : {
          "data" : [ "commerce-line-item:field-doplnkove-sluzby-item:0" ],
          "value" : "Service SLA"
        }
      },
      { "commerce_discount_extra_line_item_has_product_type" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "product_types" : { "value" : { "product" : "product" } }
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "date", "value" : "now" },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "text", "value" : [ "variable-added" ] },
          "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "commerce_order",
            "property" : "order_id",
            "value" : [ "commerce-line-item:order-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "commerce_product",
            "param_sku" : "DS-[commerce-line-item:order-id]-[conversion-result:value]",
            "param_type" : "doplnkov_slu_by",
            "param_title" : "Service SLA",
            "param_creator" : [ "site:current-user" ],
            "param_commerce_price" : { "value" : { "amount" : 100, "currency_code" : "EUR" } },
            "param_commerce_stock" : "1000"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "commerce-line-item:commerce-unit-price:amount" ],
            "op" : "*",
            "input_2" : "0.15"
          },
          "PROVIDE" : { "result" : { "result" : "Calculation result" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:commerce-price:amount" ],
          "value" : [ "result" ]
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
      { "commerce_cart_product_add_by_sku" : {
          "USING" : {
            "user" : [ "site:current-user" ],
            "sku" : "DS-[commerce-line-item:order-id]-[conversion-result:value]",
            "quantity" : "1",
            "combine" : "0"
          },
          "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
        }
      }
    ]
  }
}

```

---
Tags: commerce, rules
---


# Question
Title: Add custom text as a label in front of RSS feed icon
I want to change the label from "Subscribe to News" to "Subscribe to News Feed" displayed with RSS icon in drupal8. Also I need to open a popup window on clicking icon.

Attaching the screenshot:

Any help to figure this out?

# Answer
> 1 votes
You can see feed-icon.html.twig

you need copy `feed-icon.html.twig` in `core/modules/system/templates/feed-icon.html.twig` to `themes/yourtheme/templates/feed-icon.html.twig`

in file `themes/yourtheme/templates/feed-icon.html.twig`

```
{#
/**
 * @file
 * Default theme implementation for a feed icon.
 *
 * Available variables:
 * - url: An internal system path or a fully qualified external URL of the feed.
 * - attributes: Remaining HTML attributes for the feed link.
 *   - title: A descriptive title of the feed link.
 *   - class: HTML classes to be applied to the feed link.
 *
 * @ingroup themeable
 */
#}
<a href="{{ url }}"{{ attributes.addClass('feed-icon') }}>
  {{ 'Subscribe to News Feed'}}
</a>

```

---
Tags: 8, feeds
---


# Question
Title: Services module, custom endpoint & authentication
I have a have setup a custom endpoint via services and a REST server the custom end point looks like this,

`https://website.local/api/v1/druaplsquare`

The custom endpoint is built using the following code,

**drupalsqaure.module**

```
function drupalsquare_services_resources() {
  $resources = array();
  $resources['drupalsquare'] = array(
    'operations' => array(
         'create' => array(
             'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/drupalsquare'),
             'callback' => '_job_resource_create',
             'args' => array(
                 array(
                     'name' => 'node',
                     'optional' => FALSE,
                     'source' => 'data',
                     'description' => 'The node data to create',
                     'type' => 'array',
                 ),
             ),
             'access callback' => '_drupalsquare_resource_access'
         ),
         'delete' => array(
             'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/drupalsquare'),
             'callback' => '_job_resource_delete',
             'args' => array(
                 array(
                     'name' => 'jobref',
                     'optional' => FALSE,
                     'source' => array('path' => 0),
                     'description' => 'The job reference to delete',
                     'type' => 'string',
                 ),
             ),
             'access callback' => '_drupalsquare_resource_access'
         ),
    ),
  );
  return $resources;
}

```

**resources/drupalsquare.inc**

```
<?php

function _drupalsquare_resource_access() {
    return TRUE;
}

//function _drupalsquare_resource_retrieve($uid) {
//  $account = user_load($uid);
//
//  if (isset($account->data['checked_in'])) {
//      return array(
//          'uid' => $account->uid,
//          'name' => $account->name,
//          'last_checkin' => $account->data['checked_in'],
//      );
//  }
//  else {
//      return FALSE;
//  }
//}

function _drupalsquare_resource_checkin($JobReference, $date = NULL) {
    die(print_r($JobReference));
//  $account = user_load($uid);
//  $account->data['checked_in'] = is_null($date) ? REQUEST_TIME : $date;
//  user_save($account);
    return TRUE;
}

function _job_resource_create() {
    die("create");
}

function _job_resource_delete($jobref) {
    die("here");
}

```

I am making a cURL request this is endpoint, but I am first of all authenticating a user, and getting a token, I am then sending this token in the request header, however the endpoint above is returning,

> Access denied for user anonymous

Can anyone see any reason as why this would be happening?

# Answer
> 1 votes
In your code
Replace `'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/drupalsquare'),`
with `'file' => array('type' => 'inc', 'module' => 'NAME_OF_YOUR_MODULE', 'name' => 'resources/drupalsquare'),` It seems you're wrongly defining your INC file.

---
Tags: users, services
---


title: formatting a select custom field

text:
# Question
Title: formatting a select custom field
I created a custom field with the following definition:

```
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

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

    $element += [
      '#type' => 'select',
      '#title' => $this->t('Select item'),
      '#options' => [
        'empty' => $this->t('Select an item'),
        'key1' => $this->t('value1'),
        'key2' => $this->t('value2'),
        'key3' => $this->t('value3'),
      ],
      '#suffix' => '<div class="custom-field-widget"></div>',
      '#attributes' => ['class' => ['edit-custom-field-widget']],
      '#attached' => [
        'library' => [
          'custom_field/my_js_custom_field',
        ],
      ],
    ];

    return ['value' => $element];
  }

```

In Formatter class I wrote this:

```
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];

    foreach ($items as $delta => $item) {
        $elements[$delta] = [
          '#type' => 'html_tag',
          '#tag' => 'p',
          '#value' => $item->value,
      ];
    }
    return $elements;
  }

```

When I show content type item with my custom field I see

"**key1**" but I would like to see: "**value1**"

Is it possible to show "value1" directly or are other operations necessary?

# Answer
For the `select` Form element, the array key is the value, and the array value is the display of the option. That's why you're getting 'key1' for example.
If you want to achieve your goal you can write it this way:

```
'#options' => [
    'empty' => $this->t('Select an item'),
    $this->t('value1')->render() => $this->t('value1'),
    $this->t('value1')->render() => $this->t('value2'),
    $this->t('value1')->render() => $this->t('value3'),
],

```

Although this doesn't seem right :D
Also, while you're at it, you should check 'Select' form element documentation as you shouldn't add 'empty' value but rather use the '#empty\_value'and '#empty\_options' properties.
> -1 votes

---
Tags: plugins
---


title: How to sort the query results?

text:
# Question
Title: How to sort the query results?
In my task I need to display the results based on "the newest first". I perform a query:

```
$query = \Drupal::database()->select('node_field_data', 'node');
$query->innerJoin('node__field_ils_apps', 'app', 'app.entity_id = node.nid AND app.field_ils_apps_target_id = '.$node->id());
$query->addField('app', 'entity_id', 'nid');
$query->groupBy('app.entity_id');

$query->orderBy('created', 'DESC');
$query->execute();

```

But it returns me an error:

```
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column

```

Could you please tell me what I do wrong?

# Answer
Try this out

```
use Drupal\Core\Database\Database;

$connection = Database::getConnection();
  //- Step one get all referenced nids
  $query = $connection->select('node_field_data', 'nfd')
    ->fields('nfd', ['nid', 'created']);
   $query->innerJoin('node__field_ils_apps', 'app', 'nfd.nid = app.entity_id');
  $query->orderBy('created', 'DESC');
  $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

```
> 0 votes

---
Tags: 8, database
---


# Question
Title: Unable to fetch admin config form submitted values
I created a admin config form in drupal 8 . I am not able to fetch the saved values using this code.

```
namespace Drupal\courier_quote\Form;

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

class AlterableVariables extends ConfigFormBase {

  protected function getEditableConfigNames() {
    return [
      'courier_quote.settings',
    ];
  }

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

  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('courier_quote.settings');

    $form['Price_per_mile'] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('Price Per Mile'),
      '#default_value' => $config->get('Price_per_mile'),
    ];
    $form['minimum_del_dist'] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('Minimum Delivery Distance'),
      '#default_value' => $config->get('minimum_del_dist'),
    ];
    $form['long_dis_min_percent'] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('Long Distance Minimum Percentage'),
      '#default_value' => $config->get('long_dis_min_percent'),
    ];
    $form['business_hrs_start_time'] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('Business Hours Start Time'),
      '#default_value' => $config->get('business_hrs_start_time'),
    ];
    $form['business_hrs_end_time'] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('Business Hours End Time'),
      '#default_value' => $config->get('business_hrs_end_time'),
    ];
    $form['after_hr_surcharge'] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('After-Hours Surcharge'),
      '#default_value' => $config->get('after_hr_surcharge'),
    ];
    $form['weight_surcharge'] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('Weight Surcharge'),
      '#default_value' => $config->get('weight_surcharge'),
    ];
    $form['admin_email'] = [
      '#type'          => 'email',
      '#title'         => $config->get('admin_email'),
      '#default_value' => $config->get('admin_email'),
    ];

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

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('courier_quote.settings');
    $config->set('courier_quote.Price_per_mile', $form_state->getValue('Price_per_mile'));
    $config->save();
    return parent::submitForm($form, $form_state);
  }
}

```

# Answer
> 0 votes
You need submit form for save data

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  $this->config('courier_quote.settings')
      ->set('courier_quote.Price_per_mile', $values['Price_per_mile'])
      ->save();
}

```

You need replace

```
$form['Price_per_mile'] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('Price Per Mile'),
      '#default_value' => $config->get('Price_per_mile'),
    ];

```

to

```
$form['Price_per_mile'] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('Price Per Mile'),
      '#default_value' => $config->get('courier_quote.Price_per_mile'),
    ];

```

It's not right with your key config

# Answer
> 0 votes
In you submit function, you shouldn't `return the parent::submitForm` function but execute it in the beginning.
Also, you load the configuration object using `$this->config('courier_quote.settings')` then you access the keys directly without the dot e.g. `->set('price_per_mile', SOME_VALUE)`
Finally, you should use snake\_case in naming the configuration keys

---
Tags: 8, forms
---


title: Validation plugin for a Boolean field

text:
# Question
Title: Validation plugin for a Boolean field
I want to contextually filter my View with a boolean field, for which the "On" value is "New," so using a URL like /view/url/new.

I first tried basic validation, but that would only work if my URL were /view/url/1.

So I wrote my own validation plugin to validate "New" as if it were "1".

```
<?php

namespace Drupal\my_module_validation\Plugin\views\argument_validator;

use Drupal\views\Plugin\views\argument_validator\ArgumentValidatorPluginBase;

/**
 * Validate the New boolean.
 *
 * @ingroup views_argument_validate_plugins
 *
 * @ViewsArgumentValidator(
 *   id = "my_module_validation",
 *   title = @Translation("MYMODULE Validation")
 * )
 */
class MyModuleValidation extends ArgumentValidatorPluginBase {

  public function validateArgument($argument) {
    if($argument == 'new' || $argument == 'New' || $argument == '1') {
      return TRUE;
    }
    return FALSE;
  }
}

```

So I'm able to apply this fine (and I can tell it's being used with a drupal\_set\_message() thrown inside that block), but it still doesn't work. Results only appear if I add the /view/url/1 and not the /view/url/new like I want.

Please help me understand what I've done wrong and how I can fix it.

# Answer
If I add $this-\>argument-\>argument = '1'; to the above code, it works:

```
<?php

namespace Drupal\my_module_validation\Plugin\views\argument_validator;

use Drupal\views\Plugin\views\argument_validator\ArgumentValidatorPluginBase;

/**
 * Validate the New boolean.
 *
 * @ingroup views_argument_validate_plugins
 *
 * @ViewsArgumentValidator(
 *   id = "my_module_validation",
 *   title = @Translation("MYMODULE Validation")
 * )
 */
class MyModuleValidation extends ArgumentValidatorPluginBase {

  public function validateArgument($argument) {
    if($argument == 'new' || $argument == 'New' || $argument == '1') {
      $this->argument->argument = '1';
      return TRUE;
    }
    return FALSE;
  }
}

```
> 0 votes

---
Tags: views, 8, plugins
---


# Question
Title: How can I get the invoicing and shipping profiles for a user?
How can I get two separate profiles, one for shipping and one for invoicing? I can get the default profile for a user, but there does not appear to a type associated with it.

In Drupal 7 I could use commerce\_addressbook\_get\_default\_profile\_id to get the default profile per type, but I don't see this function or an equivalent in Commerce 2.

I'm porting a custom module from a Drupal 7 online shop to a Drupal 8 online shop. This custom module synchronizes user and order data to Navision which has separate fields for shipping and invoicing. Ideally I'd also be able to use hook\_profile\_update to sync the profile updates to Navision.

# Answer
I ended up doing this in a roundabout way:

* Get the most recent order for the user
* Get the shipping and billing profile for this order

If there are no orders, the user's unlikely to have shipping and billing info
> 0 votes

---
Tags: 8, commerce
---


title: Get link address of a file

text:
# Question
Title: Get link address of a file
I have a page A that has an inline entity form that is referencing to page B, it's possible programmatically or in another way to get the link address of a file that page A is referencing to?

# Answer
> 0 votes
Yes it is possible, but that's a quite broad question. And it depends a little bit what exactly want to achieve and *where*.

Basically when you have the node object of page B you also have the field value of the reference field, which will be a node ID. The node ID of page A. You can take this node ID to load node A – `node_load($nid)`.

Then you have the node object of node A. And from there you'll get the field value of the file field which most likely is a file ID. This file ID now can be taken to build the path to the file – `file_load($fid)`.

---
Tags: 7, nodes, files
---


# Question
Title: How to correctly use cookies? (Twig and cache context)
In my current project I need to alter node templates depending on previously visited landing page. My idea is that, when a visitor visits one of these landing pages, a cookie will be set, and subsequent node templates will be altered depending on that cookie.

I've got three view pages serving as entry points for my visitors:
myproject.com/tv
myproject.com/mobile
myproject.com/infopoint

In theme preprocess I'm checking/setting a cookie and assigning a template variable. The Twig templates do minor modifications depending on that variable:

```
function MYTHEME_preprocess(array &$variables, $hook) {
  $router = \Drupal::routeMatch();

  if ($route = $router->getRouteObject()) {
    $view_id = $route->getDefault('view_id');
    $display_id = $route->getDefault('display_id');
    $view_display_plugin = $route->getOption('_view_display_plugin_id');

    if ($view_id && $view_display_plugin === 'page') {
      if ($view_id == 'slide') {
        user_cookie_save(['device' => 'tv']);
        $variables['MYTHEME']['device'] = 'tv';
      }
      elseif ($view_id == 'tile' && $display_id == 'mobile') {
        user_cookie_save(['device' => 'mobile']);
        $variables['MYTHEME']['device'] = 'mobile';
      }
      elseif ($view_id == 'tile' && $display_id == 'infopoint') {
        user_cookie_save(['device' => 'infopoint']);
        $variables['MYTHEME']['device'] = 'infopoint';
      }
    }
  }

  // user_cookie_save prefixes all cookie names with 'Drupal.visitor.'
  if (isset($_COOKIE['Drupal.visitor.device']) &&
    in_array($_COOKIE['Drupal.visitor.device'], ['tv', 'mobile', 'infopoint'])) {
         // I'm doing design modifications in my Twig templates depending on this variable
        $variables['MYTHEME']['device'] = $_COOKIE['Drupal.visitor.device'];
    }
  }
}

```

In services.yml I've activated the cookies cache context

```
parameters:
  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions', 'url.site', 'cookies:Drupal.visitor.device']

```

In my Twig templates I've got multiple code pieces like this:

```
{% if MYTHEME.device == 'tv' %}
   <!-- code here -->
{% else %}
   <!-- other design here -->
{% endif %}

```

Sadly the code doesn't really work. On the entry pages, the `device` theme variable is always correct, but the cookie is not updated (seems as if only first uncached hit sets the cookie. I even have the weird situation that cookie and twig variable aren't equal.). On node templates the theme variable isn't set correctly at all.

Any ideas how to get the code above working?

PS: Due slow views with geo-distance calculations disabling cache is not an option, I need to provide cached pages also for anonymous users.

# Answer
> 5 votes
I've updated the code in the question, the code is now working. It was almost complete, I had made some simple mistakes though:

1. Even when providing a proper cache context, you still need to disable the `Internal page cache` module. Only `Internal dynamic page cache` module is allowed.
2. `user_cookie_save()` prefixes the cookie name with `Drupal.visitor.` This is the real name you'll also see in your browser's dev console. But when checking for cookie names in PHP, dots and spaces are converted to underscores. That means using `user_cookie_save(['mycookie' => 'some_value']);` creates a cookie with a "real" name of `Drupal.visitor.mycookie`, but in PHP
    * your template/module code needs to check
    `if ($_COOKIE['Drupal_visitor_mycookie'])`
    * and you also have to use the underscore name in services.yml
    `required_cache_contexts: ['cookies:Drupal_visitor_device', '...other_stuff...']`
3. Don't set the cookie value and check that updated cookie value in the same request:
`user_cookie_save(['mycookie' => 'new_value'])`
will immediatly update the cookie in the client browser, but PHP code in the same request like
`if ($_COOKIE['Drupal_visitor_mycookie'])`
will still return the original value from the previous request.

---
Tags: 8, theming, caching, cookies
---


# Question
Title: Close a webform when total seats reach a maximum
I would like to know if it is possible to set-up a specific event registration webform to close automatically when the number of total reserved seats (reserved seats field) reaches a certain maximum.

**A little background:** I have a few different event registration forms on my website, each event is held in a different venue with a maximum number of seats. The forms each have a reserved seats field, users can reserve up-to 2 seats(max) per submission. I cannot use the submission limit feature of the webform because the number of submissions do not map directly to the number of total seats that users are reserving.

Is it possible to have the webform calculate the sum of the reserved seats field and close the form when it reaches a certain maximum number? How would I go about setting that up?

# Answer
> 3 votes
I built a custom handler to process seat reservations. I just wanted to share my code for anyone else looking to do the same thing. @jrockowitz let me know if you want to add this into webform core.

```
<?php
namespace Drupal\webform_reservations\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
* Form submission handler.
*
* @WebformHandler(
* id = "webform_reservations_handler",
* label = @Translation("Reservations Handler"),
* category = @Translation("Form Handler"),
* description = @Translation("Manage maximum seat reservations"),
* cardinality =
 \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
* results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
* )
*/

class ReservationHandler extends WebformHandlerBase {

 /**
 * {@inheritdoc}
 */

  public function submitForm(array &$form, FormStateInterface $form_state,
  WebformSubmissionInterface $webform_submission) {
  $webform = $webform_submission->getWebform();
  $formid = $webform->id();

//query the db for all submissions of current webform submission
$query = \Drupal::entityQuery('webform_submission');
$query->condition('webform_id', $formid);
$result = $query->execute();

//load all the submissions from the results
$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);
$submission_data = array();

foreach ($submissions as $submission) {
$submission_data[] = $submission->getData();
}

$current_reserved = 0;

//add up all the values in the 'seats needed' field of each submission and save it to a variable.
for ($i = 0; $i < count($submission_data); $i++){
    $current_reserved += $submission_data[$i]['seats_needed'];
}

//when a registration form is submitted, check if the current reserved seats exceeds the value specifed in the maximum allowed seats field of the form.
if ($current_reserved >= $webform->getElement('max_seats')['#value']) {
    $webform->setStatus('closed');
    $webform->save();

 $message = 'The form has ' . $current_reserved . ' reserved seats, the max seats is currently set to ' . $webform->getElement('max_seats')['#value'] .  ' the form will now be closed';
  } else {$message = 'The form has ' . $current_reserved . ' reserved seats, the max seats is currently set to ' . $webform->getElement('max_seats')['#value'] .  ', the form will stay open';}

//log the output to the drupal logger, to indicate if the webform is still open or closed after each submission.
\Drupal::logger('webform_reservations')->info($message);

}
}
?>

```

# Answer
> 1 votes
You would have to create custom WebformHandler that calculates the sum for a specified element and closes the form. This handler could be reusable and contributed back to Drupal.

The WebformHandler would allow site builders to select the 'Number' element, specify the allows total per webform, source entity, and/or user and then block the form once the specified limit is reached.

---
Tags: webforms
---


# Question
Title: Add a default value for existing Image alt field
I have an image field in article content type and have created hundreds of nodes for article content type, but now I need to add a value for image alt fields for these existing nodes. Even the default value field for image alt is not showing when I try to edit the field.

How can I add values for the alt attribute of the image field in existing nodes?

# Answer
> 0 votes
Add a node\_preprocess function to your theme file. The logic would be to check if the current node has a value in the field for "image alt text", if not then set a default value, else return.

These are not the exact field names but this should get you started on what to look for in your code.

```
 function MYTHEME_preprocess_article(&$variables) {
      if (!field_image_alt_text->getValue().strlen() = 0 || null ) { set value to something } else {return;}
};

```

---
Tags: 7, nodes, media
---


title: Dynamically creating menu items

text:
# Question
Title: Dynamically creating menu items
What I need is to add menu item to some menu, but it should have different parameters (title and url) depending on language. So I created new module and added `links.menu.yml` like:

```
my_menu_item_id:
  title: 'Dummy Title'
  description: 'Dummy Description'
  url: http://www.google.com
  parent: mainmenu
  menu_name: mainmenu
  weight: -100

```

And item appears well. Then I added `menu_links_discovered_alter` hook like:

```
    function mymodule_menu_links_discovered_alter(&$links) {
      $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
      $links['my_menu_item_id']['title'] = 'Title:'.$language;
    }

```

And title really get's altered, but that renaming is cached. So when I visit some page in other language previous title remains until I clear the cache. How to solve this. How to make Drupal execute this code with every page instead of using cached value?

# Answer
The discovery process is not the right place for dynamic behavior. A menu link defined statically in a yaml file can provide dynamic values only in a menu link plugin class.

In your case you would implement the method `MenuLinkInterface::getTitle`:

```
  public function getTitle() {
    return $title;
  }

```

See this answer https://drupal.stackexchange.com/a/249342/47547 for a complete example of a menu link class.

Although for translating the title this should not be necessary, titles of routes and menu links are covered by interface translation, see Translate routing and menu titles
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: 'hook_entity_operation_alter', but for users
I'd like to customise the Operations dropdowns on */admin/people*

The documentation for **hook\_entity\_operation\_alter()** says the second parameter should be:

*\Drupal\Core\Entity\EntityInterface $entity:*

However when I do:

```
function mymodule_entity_operation_alter(array &$operations, EntityInterface $entity) {
    kint( $entity );
}

```

I get:

> Argument 2 passed to mymodule\_entity\_operation\_alter() must be an instance of EntityInterface, instance of Drupal\user\Entity\User given

Is there anything else I can use?

# Answer
> 2 votes
*mymodule.module* also needs:

```
use Drupal\Core\Entity\EntityInterface;

```

Credits to drupality, who first mentioned this in a comment below my question

---
Tags: 8, hooks
---


# Question
Title: How to add css files based on breakpoint in library?
We have the following `mytheme.breakpoints.yml` file and a simple library `mylibrary` that is added through our `mytheme`. Within the `mylibrary` there are two libraries, one that is optimized for `desktop small` and another for `mobile` breakpoints.

How would I add the `mobile` css file only for when the browser's breakpoint is less than `756px`, but load `desktop small` breakpoint when browser's breakpoint is greater than `756px`?

**mytheme.breakpoints.yml**

```
mytheme.mobile
  label: mobile
  mediaQuery: 'all and (max-width: 756px)'
  weight: 1
  multipliers:
    - 1x
mytheme.desktopSmall
  label: desktop small
  mediaQuery: 'all and (min-width: 756px)'
  weight: 1
  multipliers:
    - 1x

```

**mytheme.libraries.yml**

```
mylibrary:
  version: 1.0
  css:
    theme:
      css/some/path/desktop-small.min.css: { /* load only for min width > 756px*/ }
      css/some/path/mobile.min.css: { /* load only for max width < 756px*/ }

```

Adding Use Theme Breakpoints as Media Queries for Theme CSS Libraries for reference.

# Answer
This is the solution I found.

### mytheme.libraries.yml

```
mylibrary:
  version: 1.0
  css:
    theme:
      css/some/path/desktop-small.min.css: { media: "all and (min-width: 756px)" }
      css/some/path/mobile.min.css: { media: "all and (max-width: 755px)" }

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How do I pass a CSS class to the controller?
I want to pass a CSS class to a controller.

In the case of nodes, I am using the following code.

```
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
  $variables['attributes']['class'][] = 'node-' . $node->id();
}

```

Is there any way to pass a CSS class to a generic controller?

# Answer
You can use this helper function to get entity from page :
Posted on Drupal Forum get\_page\_entity

* Hook implementation.

```

    /**
     * Implements hook_preprocess_html().
     */
    function YourThemeName_preprocess_html(&$variables) {
      //- Call Helper function.
      $entity = get_page_entity();
     if($entity) {
        $variables['attributes']->addClass($entity->getEntityTypeId() . '-' . $entity->id());
      }
    }

```
* Helper Function.

```

    use Drupal\Core\Entity\EntityInterface;
    /**
     * @return array|bool|\Drupal\Core\Entity\EntityInterface|mixed|null
     */
    function get_page_entity() {
      $page_entity = &drupal_static(__FUNCTION__, NULL);
      if (isset($page_entity)) {
        return $page_entity ?: NULL;
      }
      $current_route = \Drupal::routeMatch();
      foreach ($current_route->getParameters() as $param) {
        if ($param instanceof EntityInterface) {
          $page_entity = $param;
          break;
        }
      }
      if (!isset($page_entity)) {
        // Some routes don't properly define entity parameters.
        // Thus, try to load them by its raw Id, if given.
        $entity_type_manager = \Drupal::entityTypeManager();
        $types = $entity_type_manager->getDefinitions();
        foreach ($current_route->getParameters()->keys() as $param_key) {
          if (!isset($types[$param_key])) {
            continue;
          }
          if ($param = $current_route->getParameter($param_key)) {
            if (is_string($param) || is_numeric($param)) {
              try {
                $page_entity = $entity_type_manager->getStorage($param_key)
                  ->load($param);
              } catch (\Exception $e) {
              }
            }
            break;
          }
        }
      }
      if (!isset($page_entity) || !$page_entity->access('view')) {
        $page_entity = FALSE;
        return NULL;
      }
      return $page_entity;
    }

```
> 1 votes

# Answer
Try to implement template\_preprocess\_html something like this:

```
function YourThemeName_preprocess_html(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
    $variables['attributes']->addClass('node-' . $node->id());
  }
}

```
> -1 votes

---
Tags: page-controller
---


# Question
Title: Why do I get this error when I save my custom field?
I created a custom field and this is its `formElement()` method.

```
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $value = isset($items[$delta]->value) ? $items[$delta]->value : '';
  $client = \Drupal::httpClient();
  $request = $client->get('http://localhost:8083/regionilist');
  $response = json_decode($request->getBody());

  $element += [
    '#type' => 'select',
    '#title' => $this->t('Select element'),
    '#options' => $response,
    //'#options' => [
    //  'Abruzzo' => $this->t('Abruzzo label'),
    //  'Lazio' => $this->t('Lazio label'),
    //  'Sicilia' => $this->t('Sicilia label'),
    //],
    '#suffix' => '<div class="custom-field-widget"></div>',
    '#attributes' => ['class' => ['edit-custom-field-widget']],
    '#attached' => [
      'library' => [
        'custom_field/my_js_custom_field',
      ],
    ],
  ];

  return ['value' => $element];
}

```

The Rest service output is this.

```
{
  "Abruzzo": "Abruzzo label",
  "Lazio": "Lazio label"
}

```

The output of `json_decode()` is the following one.

```
array (
  'Abruzzo' => 'Abruzzo label',
  'Lazio' => 'Lazio label',
)

```

When I add the field to a content type I get the following error.

> TypeError: Argument 1 passed to Drupal\Core\Form\OptGroup::flattenOptions() must be of the type array, object given, called in C:\xampp\htdocs\drupal8DPC\core\lib\Drupal\Core\Form\FormValidator.php on line 340 in Drupal\Core\Form\OptGroup::flattenOptions() (line 23 of core\lib\Drupal\Core\Form\OptGroup.php).
> Drupal\Core\Form\OptGroup::flattenOptions(Object) (Line: 340)
> Drupal\Core\Form\FormValidator-\>performRequiredValidation(Array, Object) (Line: 247)
> Drupal\Core\Form\FormValidator-\>doValidateForm(Array, Object) (Line: 239)
> Drupal\Core\Form\FormValidator-\>doValidateForm(Array, Object) (Line: 239)
> Drupal\Core\Form\FormValidator-\>doValidateForm(Array, Object) (Line: 239)
> Drupal\Core\Form\FormValidator-\>doValidateForm(Array, Object) (Line: 239)
> Drupal\Core\Form\FormValidator-\>doValidateForm(Array, Object, 'field\_config\_edit\_form') (Line: 119)
> Drupal\Core\Form\FormValidator-\>validateForm('field\_config\_edit\_form', Array, Object) (Line: 571)
> Drupal\Core\Form\FormBuilder-\>processForm('field\_config\_edit\_form', Array, Object) (Line: 314)
> Drupal\Core\Form\FormBuilder-\>buildForm('field\_config\_edit\_form', Object) (Line: 74)
> Drupal\Core\Controller\FormController-\>getContentResult(Object, Object) call\_user\_func\_array(Array, Array) (Line: 123)
> Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() (Line: 582)
> Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 124)
> Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) (Line: 97) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() (Line: 151)
> Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 68)
> Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57)
> Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47)
> Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 99)
> Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 78)
> Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47)
> Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 38)
> Drupal\webprofiler\StackMiddleware\WebprofilerMiddleware-\>handle(Object, 1, 1) (Line: 50)
> Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23)
> Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 664)
> Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

Error does not occur when I use the fixed code (commented in the code above) instead of the REST service.

# Answer
> 0 votes
Use the Json class in core, it’s set up to use associative arrays (rather than the default object from json\_decode, which is causing your current issue):

```
$decoded = \Drupal\Component\Serialization\Json::decode(...);

```

---
Tags: 8, plugins
---


# Question
Title: Where to find all possible keys for BaseFieldDefinition -> setSettings()
I am a noob to Drupal. I am trying to create a module and am currently in the process of creating a content entity and defining its base fields. Can anyone tell me where I can find a list of possible keys for the setSetting method? In other modules I have seen things like:

```
 BaseFieldDefinition::create('entity_reference')
  ...
  ...
  ...
  ->setSetting('target_type', 'commerce_store')
  ->setSetting('handler', 'default')

```

How is it that the module creator knew to use target\_type and handler?? Any help is much appreciated. I am very confused.

# Answer
The settings are specific to each field type, and each type can provide both storage and field settings (storage settings apply to the field as a whole, per type of entity it's used in, and field settings are the per-bundle settings).

For example, the `entity_reference` type, backed by the `EntityReferenceItem` class, provides a `target_type` storage setting, and several field settings (including `handler`).

You can use the API to get the default settings, which equate to the available settings that you're looking for, like this:

```
$field_type_manager = \Drupal::service('plugin.manager.field.field_type');
$storage_settings = $field_type_manager->getDefaultStorageSettings('entity_reference');
$field_settings = $field_type_manager->getDefaultFieldSettings('entity_reference');

```

That gets you something like this:

If you need to inspect the code to find out what's going on, you can find the class responsible for a particular field type with the same service:

```
$class = $field_type_manager->getDefinition('entity_reference')['class'];

```
> 3 votes

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


# Question
Title: Where does the value of entity come from in a field of a content type?
Where does the value of entity come from in a field of a content type?

I am trying to understand how the property (if it is a property) entity is related to the field.

This question is more informative, I describe my case below.

I have a type of content **News**, in this I added field of type **image** called **"field\_image"** with a limit of a **single** value.

Type of content: News Field: field\_image

**Debuggin:**

I programmatically load the node:

```
// Return Drupal\node\Entity\Node;
$node = $this->entityTypeManager->getStorage("node")->load(1);

// {\Drupal\file\Plugin\Field\FieldType\FileFieldItemList}
kint($node->field_image);

// {Drupal\file\Entity\File}
kint($node->field_image->entity); // from where comes from entity?

```

From the last example I show above **($node-\>field\_image-\>entity)**, where does the property entity appear, how can field\_image access it and know that it is a file type field?

I'm just trying to understand these internal Drupal relationships. Thank you very much for helping me understand this. regards

# Answer
> 1 votes
It's literally magic (well, PHP magic methods anyway).

`FieldItemBase` implements `__get()`, which will respond to any property on the object (existing or not):

```
public function __get($name) {
  // There is either a property object or a plain value - possibly for a
  // not-defined property. If we have a plain value, directly return it.
  if (isset($this->properties[$name])) {
    return $this->properties[$name]->getValue();
  }
  elseif (isset($this->values[$name])) {
    return $this->values[$name];
  }
}

```

And the image field type extends the entity reference field type, which maintains an `entity` property (see `EntityReferenceItem::propertyDefinitions`).

So when you request the non-existent `entity` property on the field class, `FieldItemBase` hooks it up for you via the `$properties` array, and you get an entity back.

---
Tags: 8, entities
---


# Question
Title: Prevent access to or redirect /user page
I'm looking to redirect or prevent access for authenticated users to the `/user` page. The reason being that it serves no purpose being there so would like to either remove or redirect it.

The best I've managed so far is to redirect the user on login so they don't get dropped on the `/user` page straight after logging in which works great but I'd like to prevent all access to it. The code I've used for the redirect is below:

```
function mymodule_user_login($account) {
  // Redirect users on login
  $link = Link::createFromRoute(
    "Admin",
    "admin.home"
  )->getUrl()->toString();

  $homeResponse = new RedirectResponse("{$link}");
  $homeResponse->send();

  return;
}

```

Just a note for anyone potentially using the above code - it only works in a .module file, not a .theme file which took me a while to work out.

# Answer
You can probably use access\_filter to prevent access to a specific URL.

It can setup filters that will allow you to deny access to specific URL based on IP (or all IPs) and specify where to redirect anyone who is trying to access that URL.
> 0 votes

---
Tags: 8, users, redirection
---


# Question
Title: Unable to send xml response in drupal custom menu callback function and it results in failure message
```
function custom_changes_menu(){

   $items['broadbean-jobs'] = array(
    'page callback' => 'custom_changes_broadbean_interface_create_update',
    'access callback' => TRUE,
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function custom_changes_broadbean_interface_create_update(){
  header("Content-type: text/xml; charset=utf-8");
  return custom_changes_broadbean_interface_create();
}

function custom_changes_broadbean_interface_create(){

    http_response_code(200);
    $response = '<?xml version="1.0" encoding="UTF-8"?>
    <job>
    <success>true</success>
    </job>';
    return $response;

}

```

XML Response expected is as mentioned below

I still get failure message and hence response does not seem to be sent properly When using postman app to test it, the response I get is as seen here.

```
<!DOCTYPE html>
<html lang="en" dir="ltr" prefix="content: http://purl.org/rss/1.0/modules/content/ dc: http://purl.org/dc/terms/ foaf: http://xmlns.com/foaf/0.1/ og: http://ogp.me/ns# rdfs: http://www.w3.org/2000/01/rdf-schema# sioc: http://rdfs.org/sioc/ns# sioct: http://rdfs.org/sioc/types# skos: http://www.w3.org/2004/02/skos/core# xsd: http://www.w3.org/2001/XMLSchema#">
<head>
  <link rel="profile" href="http://www.w3.org/1999/xhtml/vocab" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="https://www.example.com/sites/default/files/favicon.ico" type="image/vnd.microsoft.icon" />
<meta name="Generator" content="Drupal 7 (http://drupal.org)" />
  <title>Example</title>
  <style>
@import url("https://www.example.com/modules/system/system.base.css?pem64p");
</style>
<style>
@import url("https://www.example.com/modules/field/theme/field.css?pem64p");
@import url("https://www.example.com/modules/node/node.css?pem64p");
@import url("https://www.example.com/sites/all/modules/views/css/views.css?pem64p");
@import url("https://www.example.com/sites/all/modules/ckeditor/css/ckeditor.css?pem64p");
</style>
<link type="text/css" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" media="all" />
<link type="text/css" rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:400,700|Roboto:400,700" media="all" />
<style>
@import url("https://www.example.com/sites/all/modules/ctools/css/ctools.css?pem64p");
</style>
<link type="text/css" rel="stylesheet" href="//cdn.jsdelivr.net/bootstrap/3.0.2/css/bootstrap.css" media="all" />
<style>
@import url("https://www.example.com/sites/all/themes/bootstrap/css/3.0.2/overrides.min.css?pem64p");
@import url("https://www.example.com/sites/all/themes/example/css/style.css?pem64p");
</style>
  <!-- HTML5 element support for IE6-8 -->
  <!--[if lt IE 9]>
    <script src="https://cdn.jsdelivr.net/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
  <![endif]-->
  <script src="https://www.example.com/sites/all/modules/jquery_update/replace/jquery/1.10/jquery.min.js?v=1.10.2"></script>
<script src="https://www.example.com/misc/jquery.once.js?v=1.2"></script>
<script src="https://www.example.com/misc/drupal.js?pem64p"></script>
<script src="//cdn.jsdelivr.net/bootstrap/3.0.2/js/bootstrap.js"></script>
<script src="https://www.example.com/sites/all/modules/google_analytics/googleanalytics.js?pem64p"></script>
<script>(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,"script","https://www.google-analytics.com/analytics.js","ga");ga("create", "UA-70937835-1", {"cookieDomain":"auto"});ga("send", "pageview");</script>
<script>jQuery.extend(Drupal.settings, {"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"example","theme_token":"shC7kxGGkqtdkbNgLM15MiSaQ876Ge9x0To_I-xoDoM","js":{"sites\/all\/themes\/bootstrap\/js\/bootstrap.js":1,"sites\/all\/modules\/jquery_update\/replace\/jquery\/1.10\/jquery.min.js":1,"misc\/jquery.once.js":1,"misc\/drupal.js":1,"\/\/cdn.jsdelivr.net\/bootstrap\/3.0.2\/js\/bootstrap.js":1,"sites\/all\/modules\/google_analytics\/googleanalytics.js":1,"0":1},"css":{"modules\/system\/system.base.css":1,"modules\/field\/theme\/field.css":1,"modules\/node\/node.css":1,"sites\/all\/modules\/views\/css\/views.css":1,"sites\/all\/modules\/ckeditor\/css\/ckeditor.css":1,"\/\/maxcdn.bootstrapcdn.com\/font-awesome\/4.3.0\/css\/font-awesome.min.css":1,"\/\/fonts.googleapis.com\/css?family=Open+Sans:400,700|Roboto:400,700":1,"sites\/all\/modules\/ctools\/css\/ctools.css":1,"\/\/cdn.jsdelivr.net\/bootstrap\/3.0.2\/css\/bootstrap.css":1,"sites\/all\/themes\/bootstrap\/css\/3.0.2\/overrides.min.css":1,"sites\/all\/themes\/example\/css\/style.css":1}},"googleanalytics":{"trackOutbound":1,"trackMailto":1,"trackDownload":1,"trackDownloadExtensions":"7z|aac|arc|arj|asf|asx|avi|bin|csv|doc(x|m)?|dot(x|m)?|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt(x|m)?|pot(x|m)?|pps(x|m)?|ppam|sld(x|m)?|thmx|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls(x|m|b)?|xlt(x|m)|xlam|xml|z|zip"},"bootstrap":{"anchorsFix":1,"anchorsSmoothScrolling":1,"formHasError":1,"popoverEnabled":1,"popoverOptions":{"animation":1,"html":0,"placement":"right","selector":"","trigger":"click","triggerAutoclose":1,"title":"","content":"","delay":0,"container":"body"},"tooltipEnabled":1,"tooltipOptions":{"animation":1,"html":0,"placement":"auto left","selector":"","trigger":"hover focus","delay":0,"container":"body"}}});</script>
</head>
<body class="html not-front not-logged-in no-sidebars page-broadbean-jobs">
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable">Skip to main content</a>
  </div>
    <header id="navbar" role="banner" class="navbar container navbar-default">
  <div class="container">
    <div class="navbar-header">
            <a class="logo navbar-btn pull-left" href="/" title="Home">
        <img src="https://www.example.com/sites/default/files/example-logo.png" alt="Home" />
      </a>

      <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

          <div class="navbar-collapse collapse">
        <nav role="navigation">
                        <div class="region region-navigation">
    <section id="block-block-1" class="block block-block clearfix">

  <div class="jkInfoBlock"><i class="fa fa-phone"></i> <a href="tel:+61353329955">03 5332 9955</a></div>

</section>
  </div>
                              <ul class="menu nav navbar-nav"><li class="first collapsed"><a href="/employees/vacancies-and-employee-services" class="fa fa-search">Candidates</a></li>
<li class="collapsed"><a href="/employers/why-jk-personnel" class="fa-users fa">Employers</a></li>
<li class="leaf"><a href="/content/about-us" class="fa fa-info-circle">About Us</a></li>
<li class="last leaf"><a href="/content/contact-us" class="fa fa-phone-square">Contact Us</a></li>
</ul>                            </nav>
      </div>
      </div>
</header>
<div class="main-container container">

  <div class="row">

    <section class="col-sm-12">
                  <a id="main-content"></a>
                                                                <div class="region region-content">
    <section id="block-system-main" class="block block-system clearfix">

  <?xml version="1.0" encoding="UTF-8"?>
                         <job>
                           <success>true</success>
             </job>
</section>
  </div>
    </section>

  </div>
</div>
<footer class="footer container">
    <div class="region region-footer">
    <section id="block-block-3" class="block block-block col-md-6 clearfix">

  <p>Copyright © 2018, JK Personnel | All Rights Reserved<br />
Website Planning, Production and Online Marketing by <a href="http://nbs.digital" target="_blank">NBS Digital</a></p>

</section>
<section id="block-menu-block-4" class="block block-menu-block col-md-6 clearfix">

  <div class="menu-block-wrapper menu-block-4 menu-name-menu-footer-menu parent-mlid-0 menu-level-1">
  <ul class="menu nav"><li class="first leaf menu-mlid-571"><a href="/content/timesheets">Timesheets</a></li>
<li class="leaf menu-mlid-572"><a href="/content/privacy-policy">Privacy</a></li>
<li class="leaf menu-mlid-573"><a href="/">Terms of Use</a></li>
<li class="leaf menu-mlid-574"><a href="/content/about-us">About Us</a></li>
<li class="last leaf menu-mlid-575"><a href="/content/contact-us">Contact Us</a></li>
</ul></div>

</section>
  </div>
</footer>
  <script src="https://www.example.com/sites/all/themes/bootstrap/js/bootstrap.js?pem64p"></script>
</body>
</html>

```

**REQUIREMENT** : How to make sure the xml response sent through drupal using menu callback function is correct(right now it gives failure message).

# Answer
When you want to output a raw response you need to `print` the value and exit instead of returning.

`print custom_changes_broadbean_interface_create(); // don't just return
exit;`
> 1 votes

---
Tags: 7
---


title: File migration create ghost files

text:
# Question
Title: File migration create ghost files
I tested a migration from Drupal 6 to Drupal 8 on a local installation (2 differents multisites). Sometimes I get "ghost files" after running *upgrade\_d6\_file*.

> Processed 1444 items (1441 created, 0 updated, 3 failed, 0 ignored) - done with 'upgrade\_d6\_file'
> upgrade\_d6\_file Migration - 3 failed.

Then in admin/content/files, I get files like swadouotoclabruswuspitomiswulusliwokedaspamaslouawrotrephichophasichocutribuhostestus or wruhahachicregiwaspidristocospopowrucrekefrocojegephehoshapracocrewafrispugedrachupuclushipreclochoshusiclastewracrislumufraswiheracribra.

How can I fix this issue?

EDIT1: In my use case, with a custom node content migration.Not sure about using the Skip on empty option. However file exist, ghost files are created.

```
id: upgrade_d6_node_diapo_hp
label: Nodes
audit: true
migration_tags:
  - Drupal 6
  - Content
  - Migration_CE
migration_group: migrate_drupal_6_ce
source:
  plugin: d6_node
  node_type: diapo_hp
process:
  # In D6, nodes always have a tnid, but it's zero for untranslated nodes.
  # We normalize it to equal the nid in that case.
  # @see \Drupal\node\Plugin\migrate\source\d6\Node::prepareRow().
  # If you are using this file to build a custom migration consider removing
  # the nid and vid fields to allow incremental migrations.
  nid: tnid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: "und"
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  body/format:
    plugin: migration_lookup
    migration: d6_filter_format
    source: format
  body/value: body
  body/summary: teaser
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp

  #OK
  field_diapo_home:
    plugin: d6_field_file
    source: field_diapo_home
    process:
      target_id:
        plugin: migration_lookup
        migration: upgrade_d6_file
        source: fid
        -
        plugin: skip_on_empty
        method: process

#  unmapped d6 fields.
#  tnid
#  translate
#  moderate
#  comment

destination:
  plugin: entity:node
migration_dependencies:
  required:
    - upgrade_d6_user
    - upgrade_d6_node_type
    - upgrade_d6_node_settings
    - upgrade_d6_filter_format
  optional:
    - fields_instance_widget
    - fields_formatter_settings

```

# Answer
> 1 votes
Try it like this:

```
  field_diapo_home:
  -
    plugin: d6_field_file
    source: field_diapo_home
    migration: upgrade_d6_file
  -
    plugin: skip_on_empty
    method: process

```

---
Tags: 8, migrations
---


# Question
Title: Lost setting of the custom field when editing a page
I created a content type with my own custom field as described in Why do I get this error when I save my custom field?

The insertion of an item with this content type works, but when I want to modify the article I verified that I lose my custom field setting (it's a select box).

What is the method to keep the setting?

# Answer
According to the code in the mentioned question, you need to define `#default_value` property and assign the `$value` variable to it like this:

```
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';
    $client   = \Drupal::httpClient();
    $request = $client->get('http://localhost:8083/regionilist');
    $response = json_decode($request->getBody());

    $element += [
      '#type' => 'select',
      '#title' => $this->t('Select element'),
      '#options' => $response,
      '#suffix' => '<div class="custom-field-widget"></div>',
      '#attributes' => ['class' => ['edit-custom-field-widget']],
      '#attached' => [
        'library' => [
          'custom_field/my_js_custom_field',
        ],
      ],
      '#default_value` => $value,
    ];

    return ['value' => $element];
  }

```
> 0 votes

---
Tags: 8, plugins
---


# Question
Title: Language switcher block hides for authenticated user
I have a language switcher added to my site. It works fine as long as I'm an unauthenticated user. Logging into site replaces it with:

```
<span data-big-pipe-placeholder-id="callback=Drupal%5Cblock%5CBlockViewBuilder%3A%3AlazyBuilder&args%5B0%5D=languageswitcher&args%5B1%5D=full&args%5B2%5D&token=nsR3jJa8bJz_M5rp3ogwQZ8Ownrs-S1wckm2wsrv1BY"></span>

```

I see this behavior also when I add a `message block` to any of the regions.

I'm also using big pipe. Could it be causing some issue? Is this a bug with language switcher block?

Any help is appreciated.

Thank you

# Answer
> 0 votes
Things you can try one of the following:

* Uninstall Big Pipe module
* Try switching to another theme. It might be that the active theme has a JS error which breaks the execution of the Big Pipe
* Enable JS aggregation if disabled, or disable it if enabled
* Check for console erros in the developer tools

---
Tags: i18n-l10n, debugging
---


title: phone call Button

text:
# Question
Title: phone call Button
I am a newbies in Drupal, currently I use Drupal 7.

I want to add one button into content type, to make the phone call when user click on this button.

I use module Button Field + Rule, but I don't know how to Rule create action like the link

```
<a href="tel:1-847-555-5555">1-847-555-5555</a>

```

Anyone can help me?

Thanks

# Answer
> 0 votes
I'm not sure the desired functionality is achievable via Button Field + Rules.
What you need is to create a plain text field to store the phone number, then you need to override the field template in your theme to output it as a link.
For example, if you field name is `telephone_link`, then you should create a file `field--telephone_link.tpl.php` under the folder `YOUR_THEME/templates/field` with the following content:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <a href="tel:<?php print $item['#markup'];?>" class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></a>
    <?php endforeach; ?>
  </div>
</div>

```

---
Tags: rules
---


# Question
Title: Partial start date with end date output views
I'm using views to output a list of nodes with dates. Some node dates have both a start and end date inserted.

If both a start and end date exists, i would like the date to be outputted only taking the day from the start date.

Current: 9 January 2018 - 10 January 2018

Desired: 9 - 10 January 2018

I've tried using a custom field and rewriting the results in views, but this doesn't work. I've also looked in the pre\_render and preprocess functions and only see the start date.

Any ideas?

# Answer
> 1 votes
I have resolved this issue using the compact daterange module, and using one of the committed patches.

https://www.drupal.org/project/daterange\_compact

# Answer
> 1 votes
There is a possibility to do it without an extra module

* Add a field in views for the start date and use the custom formatter with `j` as the custom format. This will output the date without month or year.
* Add a field for end date and format this date as you wish.
* `Rewrite Results` of end date field (or add a custom field) and put the appropriate token replacements
> {{ field\_start\_date }} - {{ field\_end\_date }}

**Note:** this solution cannot handle properly dates spanning 2 or more months

---
Tags: views, 8, datetime
---


# Question
Title: Order receipt e-mail language for guest checkout
Is there a way to have the order receipt e-mail be in the language of the site version that was used for placing the order?

The order receipt e-mail that gets sent out (content of commerce-order-receipt.html.twig) for a guest is currently always in the default language. That means a user would order items from the French site, and get an English confirmation. It appears that no language data is saved for an order, so I guess there's no built-in way to do this.

Does anyone have any ideas?

# Answer
> 1 votes
This is a known problem. Orders need a language field.

That will be added as a part of https://www.drupal.org/project/commerce/issues/2603482

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


# Question
Title: how to reorganize with twig a form builded in a custom module and keep working ajax callback?
I've a form created programatically with a few fieldset and some inputs in these use ajax callback. The structure is like this :

```
$form['global']['controls'] = [
  '#type' => 'fieldset'
];

$form['global']['info'] = [
  '#type' => 'fieldset'
];

$form['global']['description'] = [
  '#type' => 'fieldset'
];

```

I've defined a theme template in my .module file and created the twig template. This is the twig template :

```
<div>
  {{ form.global.info }}
  {{ form.global.controls }}
  {{ form.global.description }}
</div>

```

The form display correctly but ajax callback don't work : the callback are executed but don't change the elements.

All callbacks work with this :

```
<div>
  {{ form }}
</div>

```

But I can't rearange the form with this twig code.

What I want is the possibility to rearange the order of the fieldsets in twig : put the fieldset 'description' before 'info', or 'controls' before 'info', etc. And keep ajax callbacks working.

Is it possible? And how?

# Answer
The solution for this case was just to add {{ form|without('global') }} at the end of the .twig file, like this :

```
<div>
  {{ form.global.info }}
  {{ form.global.controls }}
  {{ form.global.description }}
</div>
{{ form|without('global') }}

```
> 0 votes

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


# Question
Title: How to get country list array with their corresponding country codes
I have used `$countries = \Drupal\Core\Locale\CountryManager::getStandardList();` to render array of countries with country code as their keys. But when I debug the variable `$countries;` `print_r($countries);die;` it goes into infinite loop and result does not get rendered. It shows 404.

How to get country list array?

# Answer
> 3 votes
You get the infinite loop, because the country name is a translatable markup and print\_r() can't handle this object. If you cast the country name to a string, then it is printable in php:

```
 $countries = \Drupal\Core\Locale\CountryManager::getStandardList();
 foreach ($countries as $key => $value) {
   $country_name = (string) $value;
   print "$key - $country_name\n";
 }

```

This is not needed for rendering, because twig can handle this object. This is only for debugging.

# Answer
> 2 votes
`$countries = \Drupal\Core\Locale\CountryManager::getStandardList();
 foreach ($countries as $key => $value) {
 $countries[$key] = $value->__toString();
 }`
$countries will return the array.

# Answer
> 0 votes
While the other answers return you the country list, the list might not be complete. The `CountryManager` class also provides a different function `getList()`. It returns the standard list that is returned by the static function `getStandardList()`, and allows other modules to add/alter the countries in the list.

Luckily, the `CountryManager` is also registered as a service and can be used as follows:

```
$country_manager = \Drupal::service('country_manager');
$list = $country_manager->getList();
$countries = [];
foreach ($list as $key => $value) {
  $val = $value->__toString();
  $countries[$key] = $val;
}
// $countries - will contain key-valued paid of country code and name.

```

If you are using this in the controller, or any other service, it is recommended to properly inject the service following dependency injection pattern.

---
Tags: 8, location
---


title: Adding link to the main help page

text:
# Question
Title: Adding link to the main help page
I have created an help page for my module

```
function amu_hal_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.amu_hal':
       return 'some content';
  }
}

```

This does create a page at

> /fr/admin/help/amu\_hal

How can add the correspondong link on main help page

> /fr/admin/help

# Answer
i found out that the code above create automatically a link in the main help page, as long as the .info file indicate

> name: AMU HAL

and not

> name: 'AMU HAL'
> 1 votes

---
Tags: 8, hooks
---


# Question
Title: Is it possible to login as / switch to a specific user using their password hash from the DB?
I don't particularly want to enable Devel on my production environment to gain the Switch Users block. Is there a way to switch users without any additional php code?

# Answer
> 7 votes
`drush user-login` allows you to easily log in as any user.

Compared to a module that "emulates" a different users session:

The disadvantage is that this will require a separate session, often that just means a new browser (window).

The advantage is that you *know* for certain that you see what the user sees.

This will not explicitly change the password for the user but you will be able to change the password of the user once you login.

> Display a one time login link for the given user account (defaults to uid 1).
>
> Example:
>
> "drush user-login ryan"
>
> Displays a one-time login link for the user ryan.
>
> Aliases: uli

# Answer
> 9 votes
There's Masquerade.

Masquerade adds some items to the Navigation menu to allow quick switching and switching back. It also creates a "Masquerade" block for quick switching which can be added to a sidebar or elsewhere on your site. It is visible only to those users with permission to masquerade.

Another module which accomplishes something similar is Role Switcher.

--a different Dan H

# Answer
> 2 votes
I created masquerade\_drush in the Masquerade Extras suite to help this exact issue. Check it out http://dgo.to/masquerade\_extras

# Answer
> 0 votes
For everyone wanting to login as specific user you can use: `drush uli --name someuser` which will give you one time login link to login as `someuser`.

---
Tags: 7, users
---


# Question
Title: Get the value of one field from another in the same form
I have a form with multiple fields. How can I get the value of field B from within the formElement method of my widget class for field A?

# Answer
The formElement method in your widget class should include $form\_state as one of its arguments. The value of all the fields in your form should be available in the $form\_state object:

example: $form\_state-\>getValue('field\_b');
> 1 votes

# Answer
If you are writing a widget for a field that's not a good practice to make it dependent to other fields, that does not make sense at all, a widget should be independent, form\_state is passed and can be used in form element definition of a field widget but in most cases it is not used to check the data of other fields, in most cases form\_state is used in ajax callbacks when you need something like add more button or etc.

So how you should have change your widget dependent on other fields? the answer is you should use form alter solution, in this solution you can change different things about a widget, maybe the widget type at all, like if a select widget is provided with less than 2 options you can hide it as there would be no selection.
> 0 votes

---
Tags: 8, plugins
---


# Question
Title: Adding contacter's email to reply field in contact form email
In Drupal 7, when someone used our contact form, we would receive an email and could click "reply" in the email we received and have their email be in the "to" field. Since upgrading to Drupal 8, our own email shows up in the "to" field when replying to people who sent us an email through the contact box. Can anyone shed some light on how I can get the contacter's email to show up in the "to" field?

Can I set a "reply-to" field in the email to get this to work? I am using the core contact module, not webform but I am open to using the webform module if it can allow me to fix this.

# Answer
> 1 votes
You can do that with the Webform module. For a better explanation check out this: https://www.ostraining.com/blog/drupal/how-to-create-a-contact-form/

---
Tags: 8, forms, webforms
---


# Question
Title: Include third party library in custom module without composer
I have zero command line access to a remotely hosted drupal site so I'm unable to run composer. My custom module requires the ryanwinchester/hubspot-php package. Is there any way I can manually add this library to my module without having to run composer? I'm willing to do any workaround no matter how dirty or frowned upon the technique is. I am able to run composer locally so I can at least produce a vendor folder with the autoload.php included.

Could I manually include the autoload.php in my module? Is this something I could just require in every class that uses the package?

# Answer
It's quite common that production sites are unable to run composer. Even if command line access is available the site code is read-only, so composer would be unable to make any changes. Either developers have to use composer locally and upload all modules and vendor files to the production environment, or a build system takes care of that task.

Your Drupal site will only have one `vendors` folder and autoloader, which is used by Drupal and all modules; modules don't have to include the autoloader themselves.

I'm assuming you haven't used composer to set up the site initially, and have only downloaded the Drupal zip file and added your modules. Composer is unable to automatically determine dependencies from modules when using the zip file, but you can still add the dependencies yourself. From the root directory of your site (not the module with the dependency), add any required packages as a dependency to the project:

```
composer require ryanwinchester/hubspot-php

```

This will add the third-party package as a dependency of your site, install its files to the vendor directory, and also make it available to any modules.

Updating Drupal core with this setup is trickier however. You'll need to replace the `composer.json` file with the updated version to make sure that you get the correct dependencies for Drupal core, and then re-add any of your additional dependencies.

---

You can read the documentation on using Composer to manage an entire site: https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

Using drupal-composer/drupal-project instead of the Drupal core zip file will allow you to add Drupal modules with composer, as well as automatically resolve and include any dependencies of those modules.
> 2 votes

---
Tags: 8, composer
---


# Question
Title: Check if there is already a valid one-time-password -reset link
I am using drupal 7. I have this functionality that when a user clicks the reset password he gets a one time link on which if he/she clicks then they gets to some page where they can change their password.

But this functionality is somewhat need to be modified. Suppose if they don't click on one link sent to them and then again request forget password, i want to send the same on-time-password-reset link to them and not generate new one untill 24 hours or if they clicks whichever happens first.

So do we have any function which can tell us if there is already existing one-time-password-reset link in database or not and if yes how can we reuse that instead of creating new one.

Also if they clicks on the one-time-forget-password link then they should land on password reset page (it is working as expected), but they should not be able to click any other navigation icon and if they does then message should tell them that they need to reset their password first.

# Answer
In D7 one-time reset pw links are generated using the normal hashing techniques (plus a timestamp) but they are not saved in the DB (see user\_pass\_reset\_url). This means that there is no way to resend a link (without doing some major work to store this on your own). I don't see why you would care about resending the identical link, but I'm sure you have your reasons.

If they *do* click a reset password link, I would recommend that you style the password reset page using a completely different page template that does not include your navigation links (etc...) rather than trying to disable them. Just be sure to add a message with a link to the homepage (or where ever) once they successfully edit their password, or even better, do a redirect upon success.
> 0 votes

---
Tags: users
---


title: customize login error message

text:
# Question
Title: customize login error message
I'm using Omega's sub-theme 'creativpink' and ajax\_register module.

When user enters wrong user name or wrong password I want show \*'The password entered is wrong. Please retry.' instead of Drupal's default error *'Sorry, unrecognized username or password. Have you forgotten your password?'*.

I've tried with following code in my sub-theme's template.php file :

```
function _custom_validation(&$form, &$form_state){
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $query->condition('u.name', $form_state['values']['name'], '=');
  $result = $query->execute();
  $name = $result->fetchField();
  if(empty($name)){
    form_set_error('user_name', t('The password entered is wrong. Please retry.'));
  }
}
```

After saving file I entered wrong user name and password. The error message showed both default text and my custom text.

* Sorry, unrecognized username or password. Have you forgotten your password?
* The password entered is wrong. Please retry.

But I want to show only my custom error message. How to do this?

# Answer
> 1 votes
You can use function form\_get\_errors and function form\_clear\_error

```
function _custom_validation($form,$form_state){
  $errors = form_get_errors();
  if(!empty($errors)){
    $string_error = $errors['name'];
    if (strpos($string_error, 'unrecognized username or password') !== FALSE) {
      form_clear_error();
      form_set_error('name','The password entered is wrong. Please retry.');
    }
  }
}

```

# Answer
> 0 votes
The error messages thrown by Drupal core user module are defined in

```
function user_login_final_validate()

```

This can be overridden in any of your own module/theme by calling the form\_alter function and replace user\_login\_final\_validate() with your own validator.

Example below:

```
/**
 * Implements hook_form_alter().
 */
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_login':
    case 'user_login_block':
      $user_login_final_validate_index = array_search('user_login_final_validate', $form['#validate']);
      if ($user_login_final_validate_index >= 0) {
        $form['#validate'][$user_login_final_validate_index] = 'your_custom_final_validate';
  }
    break;
  }
}

function your_custom_final_validate($form, &$form_state) {
  /* Copy the code from user.module and change to your own message */
}

```

# Answer
> 0 votes
You can use one of the two methods outlined here: http://www.bluespark.com/blog/youre-doing-it-wrong-dont-hack-drupal-core-change-text

# Answer
> 0 votes
You could use the String Overrides module. According to the project page, the module "Provides a quick and easy way to replace any text on the site."

I've used it before. It is quite easy to configure and works like a charm.

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

---
Tags: users
---


# Question
Title: Selecting more then one column when groupBy is present (db_select) - Drupal 8 added 'ONLY_FULL_GROUP_BY'
In my custom Drupal 8 plug-in I perform such query:

```
$select = db_select('my_table', 'e');
$select->addField('e', 'field1');

$select->condition('field3', 'NULL', '!=');
$select->condition('field4', array(11, 12, 31, 32, 33), 'IN');

$select->groupBy("e.field1");
$select->orderBy("e.field1");
$select->orderBy("e.field5");
$entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);

```

And it works fine. It returns me all records grouped by `field1` that meets the condition, orderered. But it returns only `field1` column.

I wanted to get more columns, so I have added another `$select->addField('e', 'field2');` just after first one:

```
$select = db_select('my_table', 'e');
$select->addField('e', 'field1');
$select->addField('e', 'field2');

$select->condition('field3', 'NULL', '!=');
$select->condition('field4', array(11, 12, 31, 32, 33), 'IN');

$select->groupBy("e.field1");
$select->orderBy("e.field1");
$select->orderBy("e.field5");
$entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);

```

This time I get error:

> Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42000\]: Syntax error or access violation: 1055 Użyto 'my\_database.e.field2' bez umieszczenia w group by:

Which means "`my_database.e.field2` has been used without putting in into group by". But I don't want to group by every column I select.

Unfortunatelly Drupal 8 added `ONLY_FULL_GROUP_BY` :( Then, how can I use `groupBy` and select more then one column at the same time?

# Answer
> 1 votes
I had a similar issue just a few days ago, and the only way to solve it was to add another groupBY query for the extra addField for the e, field2 column:

```
$select->groupBy("e.field2");

```

But, both of my groupBY where similar datas, in my case, in one field it was a date in word format (11th July 2016) and the other field group, the data was in epoch time, to help ascend or descend my table.

# Answer
> 1 votes
This is pretty annoying, but it is to provide cross database compatibility for Drupal. You can get around it by adding the following to your database connection array if you only ever intend to live in MySQL compatible land:

```
'init_commands' => [
  'sql_mode' => "SET sql_mode = 'ANSI,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER'",
],

```

But I haven't yet figured out how to disable in my Kernel tests. Still getting something like "PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1055 'local.nfd.title' isn't in GROUP BY"

# Answer
> 0 votes
> Which means "my\_database.e.field2 has been used without putting in into group by". But I don't want to group by every column I select.

Whether or not you want it is not relevant in this case. Drupal enforces a stricter SQL mode in MySQL which requires exactly this. Every selected column must either be part of groupBy or you must use a function like count(), max(), group\_concat() or similar to define what value you want.

MySQL out of the box tries to be nice and just returns an arbitrary field2 value for each group but there is no guarantee that it is actually the value you want, other database backends do not.

---
Tags: 8, database
---


# Question
Title: How do I create a custom view filter for an existing field?
I ran into a problem with creating a custom view filter for an existing field for Drupal 8. I mean a filter not for fields like "nid", "title" and so on, but for fields, which were named CCK-fields first.

Could you share with me an understandable example of code, how to create this plugin?

I tried to comprehend some examples in contrib modules, like the geolocation module, but that code was very sophisticated. Also, I haven't found adequate manuals anywhere.

# Answer
If you do not need to code your Views filter, in your Articles View, you have a Filter criteria section where you may add views filters based on many different entities, including fields (what you call CCK fields)￼.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How do we pass php code as a twig variable in global custom text field of views
How can we pass this php code as a twig variable in global custom text in views without using views php module?

I have created a view of news content with masonary layout .

```
<?php
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node /'.$row->nid);
echo $language.$alias;
?>

```

I just want to render it as a twig variable in custom text field of views without creating template because i have already created a page long ago i dont want to rework by creating template.

# Answer
> 1 votes
To place PHP code in a field extend a field plugin and override `render()`. But in your case you should get the result of this code from the existing EntityLink plugin (in UI "Link to Content") and the option `output_url_as_text`. If you want to use it as Twig variable in another field, hide the entity link field from display and place it in front of the other field.

---
Tags: views, 8
---


# Question
Title: How can I prevent or limit CRON during SimpleTest?
I have a CRON job that tops up a huge cache table. Normally, it only updates a few records. But the first time it runs in a new installation, it has to load the entire table with thousands of requests to an external API. This gives SimpleTest a big overhead for any minor test in the module.

How can I skip or limit CRON when SimpleTest creates a new installation?

# Answer
> 0 votes
I assume that your module has some sort of variable to know how far back it needs to fetch data. You could initialize that in your setUp() method.

A module should not have to care if it is executed within a test or not. Instead, the test code should prepare the environment to whatever makes sense for the test.

If that for some reason doesn't work, you can add a variable\_get() based check if it should fetch data or not. That might also be useful for local development, not just automated tests.

# Answer
> 0 votes
I didn't find a way to know directly whether SimpleTest is running. For now, I am checking a role that the module creates for users. If there are no users of that role, I assume its SimpleTest running and limit my CRON.

# Answer
> 0 votes
This post is old, but for those who still search for an answer, here are the trick :

use the preloadRegistry method, and override the parent one, instead of using the setUp method. Because Drupalwebtestcase::setUp() is calling preloadRegistry before drupal\_cron\_run()

So, in your test class extending DrupalWebTestCase, add something like this for example

```
protected function preloadRegistry(){
  parent::preloadRegistry();
  variable_set('activate_mymodule_cron', false);
}

```

Then in the hook\_cron of your module : mymodule.module : mymodule\_cron() add this :

```
$active_cron = variable_get('activate_mymodule_cron', true);
if($active_cron)
   do_something();

```

---
Tags: 7, cron, testing
---


title: How to remove text from browser title?

text:
# Question
Title: How to remove text from browser title?
I'm looking for a way to change the text ' | Drupal' part from the tag for all pages to ' | ToAnyThing'. I guess it should be possible to achieve this in the admin interface somewhere, but I cannot find where.

Thanks.

# Answer
> 0 votes
This question seems somewhat off-topic as you don't know what this thing is and how to generally change that, independent from Drupal, and I'd recommend to find that out first.

But to take a shortcut from here: that's the so called meta title. And you'll be able to customize it pretty heavily by using Metatag.

> The Metatag module allows you to automatically provide structured metadata, aka "meta tags", about a website. In the context of search engine optimization, when people refer to meta tags they are usually referring to the meta description tag and the meta keywords tag that may help improve the rankings and display of a site in search engine results. In addition, the module provides support for meta tags (Open Graph Protocol from Facebook, Twitter Cards from Twitter) that allow control of how content appears when shared on social networks.

---
Tags: nodes
---


# Question
Title: How to make a user role expire after 1 year?
I'm looking for a way to make a user role expire after 1 year. In Drupal 7 there is the Role Expire module. I found this post using the Rules module. But I can't seem to figure out how to do this in Drupal 8.

More specific, what I want is for a user to buy a Commerce product when payed, the user gets a user role to read articles behind a paywall. This role should be active for a year.

The only option I found is building a custom module but I want to try and find an other to do this first. Hope someone can help with a good suggestion or a push in the right way.

# Answer
> 1 votes
Below are the following ways to do this:

1.As same as role expire another module User expire is available User Expire.

2.By using Rules module you can expire the role after 1 Year.

Try these Modules hope this will help you.

# Answer
> 1 votes
Module Role expire has now a working version for Drupal 8.

---
Tags: 8, commerce, rules
---


# Question
Title: migrate import image (image_import plugin doesn't existe)
I'm trying to import content from a csv source file, the csv file contains a field of image URL, and I'm trying to import that image using contrib modules migrate\_plus, migrate\_source\_csv, migrate\_tools.

Here is my configuration YAML file:

```
id: my_csv_import
label: Import test
migration_groups:
  - ACME import

source:
  plugin: csv
  # Full path to the file.
  path: 'news.csv'
  # Column delimiter. Comma (,) by default.
  delimiter: ','
  # Field enclosure. Double quotation marks (") by default.
  enclosure: '"'
  # The number of rows at the beginning which are not data.
  header_row_count: 1
  # The column(s) to use as a key. Each column specified will
  # create an index in the migration table and too many columns
  # may throw an index size error.
  keys:
    - Title

  constants:
    file_destination: 'public://images/'

process:
  title: Titre
  field_image:
    plugin: image_import
    source: Image
    destination: 'constants/file_destination'
    title: file_title
    alt: !title
  type:
    plugin: default_value
    default_value: posts

destination:
  plugin: entity:node

```

CSV file:

```
Titre,Image
title 1, http://my_domaine.com/images/image1.jpg
title 2, http://my_domaine.com/images/image2.jpg

```

**Question:** While executing the command line `drush mim my_csv_import` drush return the following error message:

```
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "image_import" plugin does not exist. in                                        [error]
/Users/brahim/void/Sites/news8/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php:52

```

Any help is appreciated!

# Answer
> 2 votes
Solved by installing and enabling the contrib module migrate\_file

---
Tags: 8, migrations
---


# Question
Title: Display a code snippet based on a taxonomy term
I am trying to build a node file for a content type in Drupal 7.59. I have for example a field for a taxonomy term. There is only 2 terms Expert and Guest. I want to display something on the node if this term reference choice is marked as Expert.

So I need to figure out how to write a line that checks for the value of the taxonomy term and then if it matches expert then it displays something but if it is guest it doesn't.

The field I have setup in my content type is:

* Name of field: author type
* Machine Name: field\_author\_type
* Field Type: Term reference

The root taxonomy term is Author Type and the two terms are Expert and Guest. Does anyone know how to accomplish this? I hovered over the taxonomy term I wanted to reference and it was /taxonomy/term/57/ Is 57 the actual number or do I find it elsewhere?

So far I have this which is not much and it doesn't work so it is wrong. I am really sucky at php.

```
<?php if ($content['field_authors_type']->taxonomy[57]): ?>
    Put what you want to display here
<?php endif; ?>

```

# Answer
The value you're looking for would be stored like so

```
$content["field_authors_type"]["#items"][0]["tid"]

```

You could, if you wanted to be tidier, put this `if` statement in your theme's template.php in a `template_preprocess_node` or `template_preprocess_page` function (more on that here: https://api.drupal.org/api/drupal/modules%21node%21node.module/function/template\_preprocess\_node/7.x).

You would store your boolean value `$variables['author_is_expert']` and then in your node.tpl.php, you can just use `if ($author_is_expert)`
> 0 votes

---
Tags: 7, nodes
---


title: Placing block from a module not working

text:
# Question
Title: Placing block from a module not working
I've followed the tutorial to create a custom block from https://www.drupal.org/node/2101565

My module installed fine and I can see the block in the list of available Blocks for placing, but as soon as I click "Place Block" I just see the ajax loader for about 1 second and then nothing happens, the dialog stays open and my block does not get placed. Cleared the cache etc. didn't help, the error log does not show any available messages.

My src/Plugin/Block/TestBlock.php file:

```
<?php
namespace Drupal\test_block\Plugin\Block;

use Drupal\block\BlockBase;

/**
 * Provides a 'Demo' block.
 *
 * @Block(
 *   id = "test_block",
 *   admin_label = @Translation("A Test Block"),
 * )
 */
class TestBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}
?>

```

Drupal 8.1.1

# Answer
You have an error in your block that causes a fatal error or exception.

Right click and open the place block in a new window and/or check your error logs.
> 7 votes

# Answer
I ran into this and it ended up being an error in the Annotation syntax. Specifically the opening comment of the annotation had characters after the "/\**" Make sure your block annotation starts like this:

```
 /**
  * short description of block
  *
  * @Block(
  *   id = "custom_module_block_machine_name",
  *   admin_label = @Translation("Admin interface Label"),
  *   category = @Translation("Custom Module or Category Name")
  * )
  */

```

https://www.drupal.org/node/1882526
> 0 votes

---
Tags: 8, blocks
---


# Question
Title: TinyButStrong (and OpenTbs) library not working
Download the lib from the web, script outside of Drupal with two include\_once() and it works perfectly well. But reading questions and answers here show me this is no longer an option in a Drupal 8 controller. Fine.

```
composer require tinybutstrong/tinybutstrong
composer require tinybutstrong/opentbs

```

Those 2 commands put the code in my vendor dir and eventually the autoloader (replacing include\_once) is doing its job fine : cloning all the code in my controller and I got a fatal error saying "Cannot declare class TinyButStrong\clsTbsLocator, because the name is already in use in (...)htdocs/vendor/tinybutstrong/tinybutstrong/tbs\_class.php.

I suppose now I'm missing a use statement in my controller. Tried (a lot of!) options with no luck, for example :

```
namespace TinyButStrong; # at the beginnig of vendor/.../tbs_class.php and
use TinyButStrong\clsTinyButStrong; # before my method in my controller...

```

Also, I've read "one class per file". But tbs\_class.php contains several define and 3 classes. Will I be force to cut it in several files (and forget install with composer) ?

Thanks in advance. Have a nice day.

# Answer
> 1 votes
Including a library with composer doesn't change how it works and its class/namespace structure.

It doesn't get namespaces automatically, there is no correlation between package names and namespaces.

Looking at https://github.com/Skrol29/tinybutstrong, it doesn't seem to use namespaces and has everything in a single file.

So that's exactly how you still have to use it, just refer to the global namespace with `new \clsTinyButStrong()`.

If that doesn't work then the you need to report that there as a bug, it is responsible for telling composer where to load its files.

---
Tags: 8, composer
---


# Question
Title: How to return [error] in a rest api build with view?
I have a view which gives has an input: email key

The json returns a uid.

I would like to return \[error\] when the combination email + key is not found. Currently, it is only \[\].

How to do this?

# Answer
> 0 votes
If you are using Views, I would add a "no results behavior" that outputs the error message of your choice.

---
Tags: views, 8
---


# Question
Title: How to hide certain content types from a Link field
I created a content type for my slides in a carousel. I make a view to print them all and everything works perfectly. My only problem is that I have multiple use of the Link field from core and the auto-complete form spits out my slides node and my other nodes. How can I limit which node type are shown in all Link field? It doesn't matter if it's site-wide as they will never be needed in those fields.

# Answer
The short answer is that D8 core link field will always look for all content types. You have to write custom javascript to filter it I believe. To make life easier, I would try Link Field Autocomplete Filter, but personally I like Linkit module much more for its ability to integrate with media.
> 4 votes

---
Tags: 8, nodes
---


title: Ajax Form on load Event

text:
# Question
Title: Ajax Form on load Event
Is it possible for a Drupal Ajax form to automatically fire a callback when a page is loaded?

I know this is possible using an external JS file and doing it through Drupal behaviors, however I would prefer to be able to do is straight from the Drupal form callback as this allows for less code and more security.

I am trying to do something like this:

```
$form['mark'] = ['#markup' => '<div id="mytestid">REPLACE ME</div>'];
$form['test'] = [
  '#type' => 'textfield',
  '#title' => 'My Title',
  '#ajax' => [
    'callback' => '::callback',
    'event' => 'load',
  ],
];

```

The `load` event doesn't work, which makes me think Drupal doesn't want to allow this type of functionality. When I use something like `click` or `mouseout` it does work. Is there some type of event here that I can use that will fire this ajax callback when the form loads? Or is it not possible this way?

# Answer
The load event in jQuery doesn't work with elements without URL. This is not a Drupal issue. You can't use it this way.
> 3 votes

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


title: D7 - does drush rr ALSO clear cache?

text:
# Question
Title: D7 - does drush rr ALSO clear cache?
Someone just told me that in D7, drush rr and drush cc all do the same thing. I can’t find anything that explicitly states the difference, nor can I find anything that supports such a claim. Additionally, I’ve noticed there are some changes that seem to only show up with a drush cc all, particularly changes to code. Do drush rr and drush cc all actually implement the same functionality?

# Answer
See https://drushcommands.com/drush-7x/registry-rebuild/registry-rebuild

drush rr has the option:
`--no-cache-clear : Rebuild the registry only, do not clear caches.`

`drush rr` rebuild the registry + clear the caches.
`drush cc` clear the caches only.
> 2 votes

---
Tags: 7, drush, caching
---