title: How do I add inline JavaScript and CSS?

text:
# Question
Title: How do I add inline JavaScript and CSS?
```
$hide_submit_settings = array('hide_submit' => array(
  'hide_submit_status' => variable_get('hide_submit_status', TRUE),
  'hide_submit_method' => variable_get('hide_submit_method', 'disable'),
  'hide_submit_css' => variable_get('hide_submit_css', 'hide-submit-disable'),
  'hide_submit_abtext' => t(variable_get('hide_submit_abtext', '')),
  'hide_submit_atext' => t(variable_get('hide_submit_atext', '')),
  'hide_submit_hide_css' => variable_get('hide_submit_hide_css', 'hide-submit-processing'),
  'hide_submit_hide_text' => t(variable_get('hide_submit_hide_text', 'Processing...')),
  'hide_submit_indicator_style' => t(variable_get('hide_submit_indicator_style', 'expand-left')),
  'hide_submit_spinner_color' => t(variable_get('hide_submit_spinner_color', '#000')),
  'hide_submit_spinner_lines' => (int)variable_get('hide_submit_spinner_lines', 12),
  'hide_submit_hide_fx' => t(variable_get('hide_submit_hide_fx', FALSE)),
  'hide_submit_reset_time' => (int)variable_get('hide_submit_reset_time', 5000),
);

drupal_add_js($hide_submit_settings, 'setting');

```

How do I use it in Drupal 8?

# Answer
You should read this article, how you can adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module:

https://www.drupal.org/developing/api/8/assets
> 0 votes

# Answer
Create custom hook\_theme twig file for adding CSS and JS

```
function mymodule_theme() {
    return [
        'css' => [
            'render element' => 'children',
            'variables' => array(
                'cssdata' => NULL,
            ),
        ],
        'js' => [
            'render element' => 'children',
            'variables' => array(
                'jsdata' => NULL,
            ),
        ],
    ];
}

```

**js.html.twig**

```
<style>{{ cssdata }}</style>

```

**js.html.twig**

```
<script>{{ jsdata}}</script>

```

**In render array.**

```
$output[] = [

'#theme' => 'js',

'#jsdata' => 'alert("Hello World")',

];

```
> 0 votes

# Answer
**Warning**: this may have security implications, make fully sure the $criticalCss variable contains *only* css you trust.

Just leaving a useful snippet related to inline CSS that needs to be added in \<head\>; it can be done like this:

```
use Drupal\Core\Render\Markup;

function mymodule_preprocess_html(&$variables) {
    // **WARNING**: make sure critical.css is safe (e.g. written/generated by you).
    $criticalCss = file_get_contents('path/to/critical.css');
    $variables['page']['#attached']['html_head'][] = [
    [
        '#tag' => 'style',
        '#value' => Markup::create($criticalCss),
    ],
    'critical-css',
  ];

}

```

This snippet was adapted from critical\_css.module: https://git.drupalcode.org/project/critical\_css/blob/8.x-1.x/critical\_css.module
> 0 votes

---
Tags: 8, javascript
---


# Question
Title: How can I know if a type of content is moderated?
I'm trying to find out if a type of content (not a node) is being moderated. How can I determine it?

For example:

```
function MY_MODULE_form_node_type_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   $content_type = $form_state->getFormObject()->getEntity(); // $content_type is a Drupal\node\Entity\NodeType
}

```

I can't find a way to find out if this type of content is being moderated by some type of workflow.

# Answer
You should be able to get that from `ModerationInformation:: shouldModerateEntitiesOfBundle()`, via the `content_moderation.moderation_information` service:

```
$moderation_info = \Drupal::service('content_moderation.moderation_information');
$entity_type = \Drupal::entityTypeManager()->getDefinition('node');
if ($moderation_info->shouldModerateEntitiesOfBundle($entity_type, $content_type->id())) {
  // ...
}

```
> 1 votes

---
Tags: 8, workflows
---


# Question
Title: How do I get the content type of a node entity from the $entity object?
I'm using hook\_ENTITY\_TYPE\_presave() to alter the values of nodes upon saving, but I only want to do this for a specific content type.

How do I check the content type of the $entity object? I looked at the documentation for class node and working with Entity API, but all I found was how to get the entity type, not the content type.

Given a node `$entity` object, how can I check the content type?

# Answer
If you know that you have a node, then you can use `getType()`. If you don't know that, you can use he generic method `->bundle()`. Note that the second will return the entity type in case of an entity type that doesn't have bundles, like users.

Again, my standard reference to http://wizzlern.nl/sites/wizzlern.nl/files/artikel/drupal-content-entity-8.0.pdf, it contains both methods.
> 18 votes

# Answer
Entity Type and bundle name are two things; usually you want to have both. You might e.g. have a media entity of the bundle "image". Bundle names alone may not be unique, I think you could name a content type "gallery" and also a paragraph type "gallery" without getting a validation error. So:

```
$entity->getEntityTypeId()

```

gives you the entity type: node, user, paragraph, media

```
$entity->bundle()

```

gives you the bundle name if you have one, could be "gallery" like described above. As Berdir points out, getType() only works on nodes, so getEntityTypeId() would be a replacement for that that works on all entity types.
> 9 votes

---
Tags: 8, entities
---


# Question
Title: How to use % arguments in Easy Breadcrumbs "Paths to replace with custom breadcrumbs"
I am trying to give a more logical breadcrumb flow to the Drupal Commerce 2 checkout path, as Commerce doesn't support breadcrumbs in the checkout process.

When **not** displaying the current page in Easy Breadcrumb, Drupal Commerce 2 by default it gives you a trail like this **Home \> Checkout** after progressing from the `/Cart` page to the `/Checkout` page. This redundantly brings you back to the checkout page that you are already on.

The logical flow here when excluding your current page from the crumb, should be **Home \> Cart** when you have proceeded to the `/Checkout` page from the `/Cart` page.

This Breadcrumb can be easily set in easy breadcrumbs **Paths to replace with custom breadcrumbs** as seen in the picture:

But the problem is that the order number is placed in the URL, so you would need to replace the actual order number (5 in this example) with % argument something like `/checkout/%/order_information :: Cart|/cart`

Is it possible to somehow accept % arguments in the URL's in "Paths to replace custom breadcrumbs"?

# Answer
There is a patch here in progress to allow wild cards in breadcrumbs:

https://www.drupal.org/project/easy\_breadcrumb/issues/3051106
> 1 votes

---
Tags: 8, commerce, breadcrumbs
---


# Question
Title: Is it possible to integrate Zoho CRM with Drupal Webforms?
How would one integrate Zoho CRM with the Drupal Webform module? Salesforce has a webform module that woks well. As I understand the webform module API is different to the Drupal forms API, making it more challenging. I have found an sandbox ZOHO API drupal module that seems to have lost some steam. Any pointers would be appreciated.

# Answer
Please checkout http://www.drupal.org/project/zohocrm. There isn't a submodule in there to specifically syncronize webforms, however, when you have zohocrm set up properly, it's pretty easy to use it with some custom code to send webform data to zoho. In the code below, we are inserting a Case into Zoho. You could easily modify to insert a Lead or Contact:

```
/**
 * Implements hook_webform_submission_insert().
 */
function my_module_webform_submission_insert($node, $submission) {
  $components = $node->webform['components'];

  // Get all submission values.
  $form_values = array();
  foreach ($components as $key => $component) {
    $form_values[$component['form_key']] = $component['type'] == 'textfield' ? check_plain(trim($submission->data[$key]['value'][0])) : $submission->data[$key]['value'][0];
  }

  switch($node->nid) {
    case '234':
      $notes = 'Phone: ' . $form_values['phone_number'] . "\n";
      $notes .= 'Message: ' . $form_values['message'];

      // Build Zoho data for Case.
          $data['records'][] = array(
            'Request Type' => $form_values['topic'],
            'Subject' => $form_values['subject'],
            'Description' => $notes,
          );

          // Send case data to Zoho.
          my_module_send_record($data, 'Cases', NULL, TRUE);
    break;
  }
}

/**
 * Send record to Zoho to insert or update.
 */
function my_module_send_record($data, $module, $record_id = NULL, $workflow = NULL) {
  $zoho = zohocrm_get_client();
  if ($zoho === FALSE) {
    return;
  }

  zohocrm_log($data, 'ZOHO DATA');

  $zoho->setModule($module);

  // Trigger Zoho workflow rules
  if ($workflow) {
    $params = array('wfTrigger' => 'true');
  }

  try {
    if (!empty($record_id)) {
      zohocrm_log('UPDATE RECORD');
      $response = $zoho->updateRecords($record_id, $data, $params);
    }
    else {
      zohocrm_log('INSERT RECORD');
      $params['duplicate'] = 2;
      $response = $zoho->insertRecords($data, $params);
    }

    watchdog('zohocrm', t("Successfully sent data to Zoho CRM. Zoho module: @module"), array('@module' => $module), WATCHDOG_INFO);
    zohocrm_log($result = $response->getResponse(), 'ZOHO CRM RESPONSE');

    // Let other modules process their tasks.
    module_invoke_all('zoho_record_sent', $data, $module, $result['recordId']);
  }
  catch (Exception $e) {
    drupal_set_message(t('Sending data to Zoho CRM failed. Error message: @message', array('@message' => $e->getMessage())), 'error');
    watchdog('zohocrm', t("Sending data to Zoho CRM failed. Zoho module: @module. Error message: @message"), array('@module' => $module, '@message' => $e->getMessage()), WATCHDOG_ERROR);
  }
}

```
> 1 votes

# Answer
yes it is absolutely possible to integrate zoho crm (any module) with drupal webform, Just open your webform.module from Drupal Backend and add Zoho Api method to integrate your webform data with Zoho.

`if (isset($form['#node']) && $form_id == 'webform_client_form_177') {
 $node = menu_get_object();
 $title = $node->title;
 $form['form_name'] = array(
 '#type' => 'hidden',
 '#value' => $node->title,
 );
$form['#submit'][] = 'insert_into_zoho';
 }`

insert\_into\_zoho is the simple function i created to post data into crm with api method insertRecord().
https://www.zoho.com/crm/help/api/insertrecords.html
> 0 votes

# Answer
We were able to accomplish this easily using Zapier, which has built-in Zoho integration. Zapier is a subscription service which allows you to map inputs from one source to values in another destination. Using Webform's built-in handler to POST the submission values to Zapier makes it possible to easily forward the results into a new Zoho lead.
> 0 votes

---
Tags: webforms
---


# Question
Title: Entity field query condition to match multi-value field
Using EFQ, I want to add a fieldCondition that has to match both values in a multi-value field (fixed at two values). The following doesn't seem to work:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
       ->entityCondition('bundle', 'node_type')
       ->fieldCondition('field_myfield', 'target_id', array(
          $id_1,
          $id_2
        ), '=');

```

This returns the error:

> PDOException: SQLSTATE\[21000\]: Cardinality violation: 1241 Operand should contain 1 column(s):

# Answer
```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
       ->entityCondition('bundle', 'node_type')
       ->fieldCondition('field_myfield', 'target_id', array(
          $id_1,
          $id_2
        ), 'IN');

```

For reference see https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-use-entityfieldquery-for-drupal-7
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Notice: Trying to access array offset on value of type null in while installing drupal
I am new to drupal. I have downloaded and extracted drupal into a folder. I have installed apache and PHP on my Manjaro Linux.

here is my drupal specific apache conf:-

```
 Alias /noone/blogindrupal "/srv/http/noone/blogindrupal"
 <Directory "/srv/http/noone/blogindrupal">
    AllowOverride All
    Options FollowSymlinks Indexes
    Require all granted
 </Directory>

```

When enter http://localhost/noone/blogindrupal in the browser URL bar, I get drupal installation page which following notice red box:-

```
 Notice: Trying to access array offset on value of type null in Drupal\Component\Annotation\Doctrine\DocParser->Identifier() (line 969 of core/lib/Drupal/Component/Annotation/Doctrine/DocParser.php).
Drupal\Component\Annotation\Doctrine\DocParser->Identifier() (Line: 664)
Drupal\Component\Annotation\Doctrine\DocParser->Annotation() (Line: 640)
Drupal\Component\Annotation\Doctrine\DocParser->Annotations() (Line: 338)
Drupal\Component\Annotation\Doctrine\DocParser->parse('/**
 * Defines a form element plugin annotation object.
 *
 * See \Drupal\Core\Render\Element\FormElementInterface for more information
 * about form element plugins.
 *
 * Plugin Namespace: Element
 *
 * For a working example, see \Drupal\Core\Render\Element\Textfield.
 *
 * @see \Drupal\Core\Render\ElementInfoManager
 * @see \Drupal\Core\Render\Element\FormElementInterface
 * @see \Drupal\Core\Render\Element\FormElement
 * @see \Drupal\Core\Render\Annotation\RenderElement
 * @see plugin_api
 *
 * @ingroup theme_render
 *
 * @Annotation
 */', 'class @Drupal\Core\Render\Annotation\FormElement') (Line: 495)
Drupal\Component\Annotation\Doctrine\DocParser->collectAnnotationMetadata('Drupal\Core\Render\Annotation\FormElement') (Line: 720)
Drupal\Component\Annotation\Doctrine\DocParser->Annotation() (Line: 640)
Drupal\Component\Annotation\Doctrine\DocParser->Annotations() (Line: 338)
Drupal\Component\Annotation\Doctrine\DocParser->parse('/**
 * Provides an entity autocomplete form element.
 *
 * The #default_value accepted by this element is either an entity object or an
 * array of entity objects.
 *
 * @FormElement("entity_autocomplete")
 */', 'class Drupal\Core\Entity\Element\EntityAutocomplete') (Line: 101)
Drupal\Component\Annotation\Doctrine\SimpleAnnotationReader->getClassAnnotations(Object) (Line: 125)
Drupal\Component\Annotation\Doctrine\SimpleAnnotationReader->getClassAnnotation(Object, 'Drupal\Core\Render\Annotation\RenderElement') (Line: 145)
Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions() (Line: 86)
Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() (Line: 284)
Drupal\Core\Plugin\DefaultPluginManager->findDefinitions() (Line: 175)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 110)
Drupal\Core\Render\ElementInfoManager->buildInfo('seven') (Line: 77)
Drupal\Core\Render\ElementInfoManager->getInfo('form') (Line: 812)
Drupal\Core\Form\FormBuilder->prepareForm('install_select_language_form', Array, Object) (Line: 278)
Drupal\Core\Form\FormBuilder->buildForm('Drupal\Core\Installer\Form\SelectLanguageForm', Object) (Line: 956)
install_get_form('Drupal\Core\Installer\Form\SelectLanguageForm', Array) (Line: 1376)
install_select_language(Array) (Line: 703)
install_run_task(Array, Array) (Line: 578)
install_run_tasks(Array, NULL) (Line: 117)
install_drupal(Object) (Line: 44)
Notice: Trying to access array offset on value of type null in Drupal\Component\Annotation\Doctrine\DocParser->Identifier() (line 969 of core/lib/Drupal/Component/Annotation/Doctrine/DocParser.php).
Drupal\Component\Annotation\Doctrine\DocParser->Identifier() (Line: 664)
Drupal\Component\Annotation\Doctrine\DocParser->Annotation() (Line: 640)
Drupal\Component\Annotation\Doctrine\DocParser->Annotations() (Line: 338)
Drupal\Component\Annotation\Doctrine\DocParser->parse('/**
 * Defines a render element plugin annotation object.
 *
 * See \Drupal\Core\Render\Element\ElementInterface for more information
 * about render element plugins.
 *
 * Plugin Namespace: Element
 *
 * For a working example, see \Drupal\Core\Render\Element\Link.
 *
 * @see \Drupal\Core\Render\ElementInfoManager
 * @see \Drupal\Core\Render\Element\ElementInterface
 * @see \Drupal\Core\Render\Element\RenderElement
 * @see \Drupal\Core\Render\Annotation\FormElement
 * @see plugin_api
 *
 * @ingroup theme_render
 *
 * @Annotation
 */', 'class @Drupal\Core\Render\Annotation\RenderElement') (Line: 495)
Drupal\Component\Annotation\Doctrine\DocParser->collectAnnotationMetadata('Drupal\Core\Render\Annotation\RenderElement') (Line: 720)
Drupal\Component\Annotation\Doctrine\DocParser->Annotation() (Line: 640)
Drupal\Component\Annotation\Doctrine\DocParser->Annotations() (Line: 338)
Drupal\Component\Annotation\Doctrine\DocParser->parse('/**
 * Provides a link to break a tempstore lock.
 *
 * Properties:
 * - #label: The label of the object that is locked.
 * - #lock: \Drupal\Core\TempStore\Lock object.
 * - #url: \Drupal\Core\Url object pointing to the break lock form.
 *
 * Usage example:
 * @code
 * $build['examples_lock'] = [
 *   '#type' => 'break_lock_link',
 *   '#label' => $this->t('example item'),
 *   '#lock' => $tempstore->getMetadata('example_key'),
 *   '#url' => \Drupal\Core\Url::fromRoute('examples.break_lock_form'),
 * ];
 * @endcode
 *
 * @RenderElement("break_lock_link")
 */', 'class Drupal\Core\TempStore\Element\BreakLockLink') (Line: 101)
Drupal\Component\Annotation\Doctrine\SimpleAnnotationReader->getClassAnnotations(Object) (Line: 125)
Drupal\Component\Annotation\Doctrine\SimpleAnnotationReader->getClassAnnotation(Object, 'Drupal\Core\Render\Annotation\RenderElement') (Line: 145)
Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions() (Line: 86)
Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() (Line: 284)
Drupal\Core\Plugin\DefaultPluginManager->findDefinitions() (Line: 175)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 110)
Drupal\Core\Render\ElementInfoManager->buildInfo('seven') (Line: 77)
Drupal\Core\Render\ElementInfoManager->getInfo('form') (Line: 812)
Drupal\Core\Form\FormBuilder->prepareForm('install_select_language_form', Array, Object) (Line: 278)
Drupal\Core\Form\FormBuilder->buildForm('Drupal\Core\Installer\Form\SelectLanguageForm', Object) (Line: 956)
install_get_form('Drupal\Core\Installer\Form\SelectLanguageForm', Array) (Line: 1376)
install_select_language(Array) (Line: 703)
install_run_task(Array, Array) (Line: 578)
install_run_tasks(Array, NULL) (Line: 117)
install_drupal(Object) (Line: 44)
Notice: Trying to access array offset on value of type null in Drupal\Component\Annotation\Doctrine\DocParser->Identifier() (line 969 of core/lib/Drupal/Component/Annotation/Doctrine/DocParser.php).
Drupal\Component\Annotation\Doctrine\DocParser->Identifier() (Line: 664)
Drupal\Component\Annotation\Doctrine\DocParser->Annotation() (Line: 640)
Drupal\Component\Annotation\Doctrine\DocParser->Annotations() (Line: 338)
Drupal\Component\Annotation\Doctrine\DocParser->parse('/**
 * Defines a config entity type annotation object.
 *
 * The annotation properties of entity types are found on
 * \Drupal\Core\Config\Entity\ConfigEntityType and are accessed using
 * get/set methods defined in \Drupal\Core\Entity\EntityTypeInterface.
 *
 * @ingroup entity_api
 *
 * @Annotation
 */', 'class @Drupal\Core\Entity\Annotation\ConfigEntityType') (Line: 495)
Drupal\Component\Annotation\Doctrine\DocParser->collectAnnotationMetadata('Drupal\Core\Entity\Annotation\ConfigEntityType') (Line: 720)
Drupal\Component\Annotation\Doctrine\DocParser->Annotation() (Line: 640)
Drupal\Component\Annotation\Doctrine\DocParser->Annotations() (Line: 338)
Drupal\Component\Annotation\Doctrine\DocParser->parse('/**
 * Defines the entity form mode configuration entity class.
 *
 * Form modes allow entity forms to be displayed differently depending on the
 * context. For instance, the user entity form can be displayed with a set of
 * fields on the 'profile' page (user edit page) and with a different set of
 * fields (or settings) on the user registration page. Modules taking part in
 * the display of the entity form (notably the Field API) can adjust their
 * behavior depending on the requested form mode. An additional 'default' form
 * mode is available for all entity types. For each available form mode,
 * administrators can configure whether it should use its own set of field
 * display settings, or just replicate the settings of the 'default' form mode,
 * thus reducing the amount of form display configurations to keep track of.
 *
 * @see \Drupal\Core\Entity\EntityDisplayRepositoryInterface::getAllFormModes()
 * @see \Drupal\Core\Entity\EntityDisplayRepositoryInterface::getFormModes()
 *
 * @ConfigEntityType(
 *   id = "entity_form_mode",
 *   label = @Translation("Form mode"),
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label"
 *   },
 *   config_export = {
 *     "id",
 *     "label",
 *     "targetEntityType",
 *     "cache",
 *   }
 * )
 */', 'class Drupal\Core\Entity\Entity\EntityFormMode') (Line: 101)
Drupal\Component\Annotation\Doctrine\SimpleAnnotationReader->getClassAnnotations(Object) (Line: 125)
Drupal\Component\Annotation\Doctrine\SimpleAnnotationReader->getClassAnnotation(Object, 'Drupal\Core\Entity\Annotation\EntityType') (Line: 145)
Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions() (Line: 123)
Drupal\Core\Entity\EntityTypeManager->findDefinitions() (Line: 175)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 22)
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('date_format', ) (Line: 143)
Drupal\Core\Entity\EntityTypeManager->getDefinition('date_format') (Line: 269)
Drupal\Core\Entity\EntityTypeManager->getHandler('date_format', 'storage') (Line: 208)
Drupal\Core\Entity\EntityTypeManager->getStorage('date_format') (Line: 93)
Drupal\Core\Datetime\DateFormatter->__construct(Object, Object, Object, Object, Object)
ReflectionClass->newInstanceArgs(Array) (Line: 1176)
Symfony\Component\DependencyInjection\ContainerBuilder->createService(Object, Array, 1, 'date.formatter') (Line: 634)
Symfony\Component\DependencyInjection\ContainerBuilder->doGet('date.formatter', 1) (Line: 588)
Symfony\Component\DependencyInjection\ContainerBuilder->get('date.formatter') (Line: 87)
Drupal\Core\TempStore\Element\BreakLockLink::create(Object, Array, 'break_lock_link', Array) (Line: 21)
Drupal\Core\Plugin\Factory\ContainerFactory->createInstance('break_lock_link', Array) (Line: 83)
Drupal\Component\Plugin\PluginManagerBase->createInstance('break_lock_link', Array) (Line: 141)
Drupal\Core\Render\ElementInfoManager->createInstance('break_lock_link') (Line: 111)
Drupal\Core\Render\ElementInfoManager->buildInfo('seven') (Line: 77)
Drupal\Core\Render\ElementInfoManager->getInfo('form') (Line: 812)
Drupal\Core\Form\FormBuilder->prepareForm('install_select_language_form', Array, Object) (Line: 278)
Drupal\Core\Form\FormBuilder->buildForm('Drupal\Core\Installer\Form\SelectLanguageForm', Object) (Line: 956)
install_get_form('Drupal\Core\Installer\Form\SelectLanguageForm', Array) (Line: 1376)
install_select_language(Array) (Line: 703)
install_run_task(Array, Array) (Line: 578)
install_run_tasks(Array, NULL) (Line: 117)
install_drupal(Object) (Line: 44)
Notice: Trying to access array offset on value of type null in Drupal\Component\Annotation\Doctrine\DocParser->Identifier() (line 969 of core/lib/Drupal/Component/Annotation/Doctrine/DocParser.php).
Drupal\Component\Annotation\Doctrine\DocParser->Identifier() (Line: 664)
Drupal\Component\Annotation\Doctrine\DocParser->Annotation() (Line: 640)
Drupal\Component\Annotation\Doctrine\DocParser->Annotations() (Line: 338)
Drupal\Component\Annotation\Doctrine\DocParser->parse('/**
 * Defines a translatable annotation object.
 *
 * Some metadata within an annotation needs to be translatable. This class
 * supports that need by allowing both the translatable string and, if
 * specified, a context for that string. The string (with optional context)
 * is passed into t().
 *
 * @ingroup plugin_translatable
 *
 * @Annotation
 */', 'class @Drupal\Core\Annotation\Translation') (Line: 495)
Drupal\Component\Annotation\Doctrine\DocParser->collectAnnotationMetadata('Drupal\Core\Annotation\Translation') (Line: 720)
Drupal\Component\Annotation\Doctrine\DocParser->Annotation() (Line: 1009)
Drupal\Component\Annotation\Doctrine\DocParser->PlainValue() (Line: 1061)
Drupal\Component\Annotation\Doctrine\DocParser->FieldAssignment() (Line: 991)
Drupal\Component\Annotation\Doctrine\DocParser->Value() (Line: 860)
Drupal\Component\Annotation\Doctrine\DocParser->Values() (Line: 835)
Drupal\Component\Annotation\Doctrine\DocParser->MethodCall() (Line: 746)
Drupal\Component\Annotation\Doctrine\DocParser->Annotation() (Line: 640)
Drupal\Component\Annotation\Doctrine\DocParser->Annotations() (Line: 338)
Drupal\Component\Annotation\Doctrine\DocParser->parse('/**
 * Defines the entity form mode configuration entity class.
 *
 * Form modes allow entity forms to be displayed differently depending on the
 * context. For instance, the user entity form can be displayed with a set of
 * fields on the 'profile' page (user edit page) and with a different set of
 * fields (or settings) on the user registration page. Modules taking part in
 * the display of the entity form (notably the Field API) can adjust their
 * behavior depending on the requested form mode. An additional 'default' form
 * mode is available for all entity types. For each available form mode,
 * administrators can configure whether it should use its own set of field
 * display settings, or just replicate the settings of the 'default' form mode,
 * thus reducing the amount of form display configurations to keep track of.
 *
 * @see \Drupal\Core\Entity\EntityDisplayRepositoryInterface::getAllFormModes()
 * @see \Drupal\Core\Entity\EntityDisplayRepositoryInterface::getFormModes()
 *
 * @ConfigEntityType(
 *   id = "entity_form_mode",
 *   label = @Translation("Form mode"),
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label"
 *   },
 *   config_export = {
 *     "id",
 *     "label",
 *     "targetEntityType",
 *     "cache",
 *   }
 * )
 */', 'class Drupal\Core\Entity\Entity\EntityFormMode') (Line: 101)
Drupal\Component\Annotation\Doctrine\SimpleAnnotationReader->getClassAnnotations(Object) (Line: 125)
Drupal\Component\Annotation\Doctrine\SimpleAnnotationReader->getClassAnnotation(Object, 'Drupal\Core\Entity\Annotation\EntityType') (Line: 145)
Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions() (Line: 123)
Drupal\Core\Entity\EntityTypeManager->findDefinitions() (Line: 175)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 22)
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('date_format', ) (Line: 143)
Drupal\Core\Entity\EntityTypeManager->getDefinition('date_format') (Line: 269)
Drupal\Core\Entity\EntityTypeManager->getHandler('date_format', 'storage') (Line: 208)
Drupal\Core\Entity\EntityTypeManager->getStorage('date_format') (Line: 93)
Drupal\Core\Datetime\DateFormatter->__construct(Object, Object, Object, Object, Object)
ReflectionClass->newInstanceArgs(Array) (Line: 1176)
Symfony\Component\DependencyInjection\ContainerBuilder->createService(Object, Array, 1, 'date.formatter') (Line: 634)
Symfony\Component\DependencyInjection\ContainerBuilder->doGet('date.formatter', 1) (Line: 588)
Symfony\Component\DependencyInjection\ContainerBuilder->get('date.formatter') (Line: 87)
Drupal\Core\TempStore\Element\BreakLockLink::create(Object, Array, 'break_lock_link', Array) (Line: 21)
Drupal\Core\Plugin\Factory\ContainerFactory->createInstance('break_lock_link', Array) (Line: 83)
Drupal\Component\Plugin\PluginManagerBase->createInstance('break_lock_link', Array) (Line: 141)
Drupal\Core\Render\ElementInfoManager->createInstance('break_lock_link') (Line: 111)
Drupal\Core\Render\ElementInfoManager->buildInfo('seven') (Line: 77)
Drupal\Core\Render\ElementInfoManager->getInfo('form') (Line: 812)
Drupal\Core\Form\FormBuilder->prepareForm('install_select_language_form', Array, Object) (Line: 278)
Drupal\Core\Form\FormBuilder->buildForm('Drupal\Core\Installer\Form\SelectLanguageForm', Object) (Line: 956)
install_get_form('Drupal\Core\Installer\Form\SelectLanguageForm', Array) (Line: 1376)
install_select_language(Array) (Line: 703)
install_run_task(Array, Array) (Line: 578)
install_run_tasks(Array, NULL) (Line: 117)
install_drupal(Object) (Line: 44)

```

Also if continue and enter database information and press submit button, after few seconds I get Gateway Timeout error like:-

The gateway did not receive a timely response from the upstream server or application.

# Answer
> 16 votes
I suspect you are installing Drupal (or at least trying to) on a server running PHP 7.4, which is not currently compatible with the latest version of Drupal (8.8). There is an issue on drupal.org right here that details the current problems, including yours: https://www.drupal.org/project/drupal/issues/3086374 .

The highest supported version of Drupal 8.8 is currently 7.3: https://www.drupal.org/docs/8/system-requirements/php-requirements .

---
Tags: 8, installation
---


title: MYSQL injections: Are they a threat?

text:
# Question
Title: MYSQL injections: Are they a threat?
For a while now, all my Drupal 7 and Drupal 8 instances have been under constant attack from South America or Asia, where the attacker is trying to infiltrate Drupal with MySQL injections.

The attack is done by adding some MySQL queries to at the and of the URL:

```
www.example.com/) AND 8205=8205 AND (2155=2155
www.example.com/ AND 4874=9552
www.example.com/ AND 8205=8205
www.example.com/') AND 5487=2530 AND ('Kcfy'='Kcfy
www.example.com/') AND 8205=8205 AND ('nUHc'='nUHc
www.example.com/' AND 9068=8481 AND 'wbYZ'='wbYZ
www.example.com/' AND 8205=8205 AND 'DeAs'='DeAs
www.example.com/%' AND 7985=5834 AND '%'='
www.example.com/%' AND 8205=8205 AND '%'='
www.example.com/ AND 5913=3547-- BaJk
www.example.com/ AND 8205=8205-- jBam
(SELECT (CASE WHEN (1873=3317) THEN 1873 ELSE 1873*(SELECT 1873 FROM INFORMATION_SCHEMA.CHARACTER_SETS) END))
(SELECT (CASE WHEN (9523=9523) THEN 9523 ELSE 9523*(SELECT 9523 FROM INFORMATION_SCHEMA.CHARACTER_SETS) END))
www.example.com/) AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND (3698=3698
www.example.com/ AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a)
www.example.com/') AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND ('XLCQ'='XLCQ
www.example.com/' AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND 'Witz'='Witz
www.example.com/%' AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND '%'='
www.example.com/ AND (SELECT 1687 FROM(SELECT COUNT(*),CONCAT(0x71717a6a71,(SELECT (ELT(1687=1687,1))),0x716b716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a)-- OHLo
www.example.com/) AND 3711=CAST((CHR(113)||CHR(113)||CHR(122)||CHR(106)||CHR(113))||(SELECT (CASE WHEN (3711=3711) THEN 1 ELSE 0 END))::text||(CHR(113)||CHR(107)||CHR(113)||CHR(107)||CHR(113)) AS NUMERIC) AND (3563=3563
www.example.com/ AND 3711=CAST((CHR(113)||CHR(113)||CHR(122)||CHR(106)||CHR(113))||(SELECT (CASE WHEN (3711=3711) THEN 1 ELSE 0 END))::text||(CHR(113)||CHR(107)||CHR(113)||CHR(107)||CHR(113)) AS NUMERIC)

```

Can somebody tell my, what these attacks are about? Was there a bug in Drupal making it vulnerable for those attacks? Is somebody else experiencing those attacks?

# Answer
> Can somebody tell my, what these attacks are about?

They're requests from bots fishing for vulnerabilities in your website.

> Was there a bug in Drupal making it vulnerable for those attacks?

Vulnerable to the specific attempts you've listed? Looking at the exact nature of the URLs, probably not. But there was, of course, Drupalgeddon once upon a time, so maybe.

> Is somebody else experiencing those attacks?

It's highly likely that they are. These attacks are usually orchestrated against as many potential victims as possible, and not built to target a single site. If the attacks you're experiencing were tailored, you would probably expect to see less generic and more Drupal-focused approaches.

---

You may wish to consider installing and configuring something like Fail2Ban to help with keeping the bots out.
> 4 votes

---
Tags: 8, security
---


title: REST Api user login

text:
# Question
Title: REST Api user login
I'm working on a react-native application with a clean D8 setup. I'm new to both. For some reason, my asyncstorage is being cleared on the emulator so I land on the login page even though I have an active session. So requesting a login returns a `403 - This route can only be accessed by anonymous users.` which is the normal behaviour. However, the app does not know who the user is or has any details regarding the user apart from the `xcsrf` token. I've figured, posting to `user?_format=json` redirects to the profile page of the user but the data returned is the html document.

How do I go about retrieving the details of the current logged in user without knowing their details? I'm ideally looking for a solution without any development on Drupal.

// Login

```
_authLogin = () => {
    // api = axios
    api({
        method: 'post',
        url: '/user/login?_format=json',
        headers: {
            'X-CSRF-Token' : this.props.xcsrf,
        },
        data: { "name": this.state.username, "pass": this.state.password }
    })
    .then(function(response) {
        this.props.saveUserSession(response.data).then((data) => {
            this.props.navigation.navigate('AuthLoading');
        })
        .catch((error) => {
            this.setState({ error })
        })
    }.bind(this))
    .catch(function(error) {
        if (error.response) {
            if( error.response.status == 403 ) {
                this._getLoggedInDetails();
            }
            // other error handling etc...
        } // other error handling etc...
    }.bind(this));
};

_getLoggedInDetails = () => {
    api({
        method: 'post',
        url: '/user?_format=json',
        headers: {
            'X-CSRF-Token' : this.props.xcsrf,
        },
    })
    .then(function(response) {
        // returns 200
        // but <!DOCTYPE html><html lang="en" dir="ltr" ...
    }.bind(this))
    .catch(function(error) {
        // handle errors
    });
}

```

# Answer
> 1 votes
Right, I found a solution myself. There are 2 options;

1. Views

* Create a new view with the user entity, set a filter criteria for logged in user and provide a rest export. This will return the current user object. So you can make a request to this when login returns a 403 so you can retrieve the details of the user.
2. Logout token

* Apply this patch to the user controller. This provides a new resource to get a logout token for the logged in user. So when login returns a 403, you can get a logout token at `session/logouttoken` and log the user out and login again.

---
Tags: 8
---


# Question
Title: How can I filter child terms in an exposed filter by parent term from contextual filter?
I have a vocabulary of Districts with nested taxonomy terms like below.

I have a view of taxonomy terms in Drupal 8 which has an exposed filter of all terms with parent and child. What I want is that when I add a contextual filter of term parent the **exposed filter** should only show child terms matching the parent term in the contextual filter.

For example, if the URL contains Deoghar, then the exposed filter (like below filter) should only show the term Karon as option.

# Answer
I've done this recently in a project of mine using `MYMODULE_form_views_exposed_form_alter`. The code assumes you've a view with the term ID on first position as contextual filter, e.g. `domain.com/myview/123`

```
<?php
function MYMODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $view = $form_state->getStorage('view');
  $display_id = $view['view']->current_display;

  if ($form_id == 'views_exposed_form' && $view['view']->id() == 'MY_VIEW' && $display_id == 'MY_VIEWDISPLAY') {
    if (!empty($view['view']->args) && $view['view']->args[0]) {
      //get the term ID from the contextual filter
      $contextTermId = $view['view']->args[0];
      $entriesToRemove = [];

      $currentFilterValue = $form_state->getUserInput()['FIELD_FILTER_TAXONOMY'];
      foreach ($form['FIELD_FILTER_TAXONOMY']['#options'] as $idx => $entry) {
        if ($idx === 'All') {
          //remove the old root '- Any -' option
          $entriesToRemove[] = $idx;
        }
        //the next line is a bit shaky might need rework:
        //sometimes filter entries are a stdClass,
        //but I've also seen entries as array in other exposed forms (grouped filters?)
        elseif ($entry instanceof stdClass && is_array($entry->option)) {
          $termId = key($entry->option);
          $termName = current($entry->option);
          //the context filter term is our new root, so we change its label to '- Any -'
          if ($termId == $contextTermId) {
            $form['FIELD_FILTER_TAXONOMY']['#options'][$idx]->option = [$termId => t('- Any -')];
            if (empty($currentFilterValue) || $currentFilterValue == 'All') {
              //we've removed the default empty/All entry, reset it to our newly created, faked '- Any -' category
              $form_state->setUserInput(['FIELD_FILTER_TAXONOMY' => $contextTermId]);
            }
          }
          else {
            //this is the core part: for each filter option load the term
            //and check if it is a child of the contextual filter term
            $parents = \Drupal::entityTypeManager()
              ->getStorage('taxonomy_term')
              ->loadParents($termId);
            if (!in_array($contextTermId, array_keys($parents))) {
              $entriesToRemove[] = $idx;
            }
            else {
              //optional: we are in a sub-filter now,so we no longer need the leading '-' to indicate hierarchy
              $form['FIELD_FILTER_TAXONOMY']['#options'][$idx]->option = [$termId => trim(preg_replace('/^-/', '', $termName))];
            }
          }
        }
      }
      foreach ($entriesToRemove as $idx) {
        unset($form['FIELD_FILTER_TAXONOMY']['#options'][$idx]);
      }
      //optional: if there is only 1 entry left, hide the filter
      if (count($form['FIELD_FILTER_TAXONOMY']['#options']) == 1) {
        $form['FIELD_FILTER_TAXONOMY'] = [
          '#type' => 'hidden',
          'value' => $contextTermId
        ];
      }
    }
  }
}

```

A word of caution: Don't to this on huge taxonomies, my code loads *every* taxonomy term to decide if it needs to be removed.
> 1 votes

# Answer
As @Hudri said, you can use `MYMODULE_form_views_exposed_form_alter()` to alter the form.

Rather than check each term to see if it's parent is your contextual filter argument, another approach might be to use the `TermStorage::loadTree()` method to load the tree of terms below a term, e.g.

```
$vocabulary_id = 'tags';
// Get this from your view object's contextual argument, e.g. $view->args[0], etc
$parent_id = 11;

$child_terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadTree($vocabulary_id, $parent_id);

// Next build an options array of the child terms.
$child_term_options = [];
// Maybe you want an Any option
$child_term_options[''] = '- Any -';
foreach ($child_terms as $term) {
  $child_term_options[$term->tid] = $term->name;
}

// Next update your filter options with only the child terms:
$form['MY_EXPOSED_FILTER']['#options'] = $child_term_options;

```
> 0 votes

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


title: How to add Download link to File field

text:
# Question
Title: How to add Download link to File field
I would like to know how I can make File field type display the upload as a download link, instead of having a link. So that user can just click and it will download).

The file field type, I added to a custom Content Type, which I created programmatically through a module.

Currently it looks like below, when I click the link, it takes to the uploaded file page. I would like to have it download instead.

Or maybe is there a way to change the view or add additional view to File types for download? or maybe change view for Content Type where it displays the Download link for the file?

# Answer
If you don't need to update the link tag, then just use the `download` attribute, it should do the trick.

I've wrote a tiny Fiddle for you https://jsfiddle.net/45ug9p7t/1/

Keep in mind that not every browser has implemented this, check it out
> 0 votes

---
Tags: views, 8, files
---


title: Solr search with exact match

text:
# Question
Title: Solr search with exact match
I am using drupal 8, search api and solr on our site. In views, I am using full text search with direct query option. Search is working for multiple words. What I want is when I search with double quote, I want the result with exact match of query string. But putting double quote doesn't seem to have any effect on it. If I changed parse mode to multiple words, double quotes work but it doesn't return any result for query without double quotes. Can I even achieve it in single view display? Any workaround suggestion so that it works for query without double quotes but also respect double quotes to do exact match depending upon query.

# Answer
Take a look at this issue:

keys of fulltext searches must be encoded as phrases for terms parse mode

A quick read indicates that you might be able to just escape the spaces, e.g foo\ bar.

Also see the view settings image in comment #10 of that issue.
> 2 votes

---
Tags: 8, search
---


# Question
Title: Show multiple drupal 7 'name field' in one view row?
Using this on D7: https://www.drupal.org/project/name

The name field is on a 'book' content type. 1-to-many authors.

In views, I want to see the name of the book, and the authors. Currently, it shows one repeat row per author. How do I consolidate them into one row? The field setting does not seem to include anything for this.

Thanks, sorry if this is noob of the century territory.

# Answer
> 0 votes
The views aggregator plus module solved my problem https://www.drupal.org/project/views\_aggregator

---
Tags: views
---


# Question
Title: How to create translations programmatically?
I have a batch in which i'm importing nodes from REST webservices. My application has two languages, FR and EN (default is FR). So, I'm creating the node in FR, then, I loop through all other languages (just EN for now) and try to do as following :

```
$languages = \Drupal::languageManager()->getLanguages();
unset($languages['fr']);

foreach ($languages AS $langcode => $language) {
  if ($node->hasTranslation($langcode)) {
    $node_translation = $node->getTranslation($langcode);
  } else {
    $node_translation = $node->addTranslation($langcode, $node->toArray());
  }

  $node_translation->status = 1;
  $node_translation->title = 'title en';
  $node_translation->subtitle = 'subtitle en';
  $node_translation->save();
}

```

And it crashes with a 500 error, reporting :

```
 - Drupal\Core\Entity\EntityStorageException : Invalid translation language (und) specified. dans Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (ligne 805 de /.../web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
 - InvalidArgumentException : Invalid translation language (und) specified. dans Drupal\Core\Entity\ContentEntityBase->getTranslation() (ligne 783 de /.../web/core/lib/Drupal/Core/Entity/ContentEntityBase.php).

```

I'm pulling my hair out on this issue for days and can not understand why the error message tells me $langcode equals `'und'` whereas a `var_dump` of it just before this line returns me `'en'`.

---

**Edit** : I tried to hardcode and remove the foreach. So just after the $node-\>save() :

```
$node_translation = $node->addTranslation('en', $node->toArray());
$node_translation->set('title', 'title en');
$node_translation->set('field_sub_title', 'subtitle en');
$node_translation->save();

```

This time, the error is the following :

```
InvalidArgumentException : Invalid translation language (en) specified.
dans Drupal\Core\Entity\ContentEntityBase->addTranslation() (ligne 863
de /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Entity/ContentEntityBase.php).

```

# Answer
After several days, I finally found the solution. Obviously, there is a bug with Drupal (here 8.4.0).

The `hasTranslation()` method don't work properly. Instead, you should use EntityManager::getTranslationFromContext() (will be deprecated in Drupal 9 though).

You can also write a new method like this one to replace it:

```
/**
 * Check if a node as a translation for the given language.
 *
 * @param object $node
 *   The node object.
 * @param string $langcode
 *   The langcode.
 *
 * @return bool
 *   True (exists) or false (does not exist).
 */
function has_translation($node, $langcode) {
  $existing_translation = \Drupal::service('entity.repository')->getTranslationFromContext($node, $langcode);
  return ($existing_translation->langcode->value === $langcode) ? TRUE : FALSE;
}

```

So, my corrected code is the following:

```
if (has_translation($node, $langcode)) {
  $node_translation = $node->getTranslation($langcode);
  $node_translation->title = 'title en';
  $node_translation->field_sub_title = 'subtitle en';
  $node_translation->status = NodeInterface::PUBLISHED;
}
else {
  $node->addTranslation($langcode, $values);
}

$node->save();

```
> 5 votes

# Answer
You can try with simple code:

```
$node = Node::load(1);
if (!$node->hasTranslation('en')) {
    $translation = $node->addTranslation('en', $node->toArray());
    $node->save();
}

```

You can't translate just because you wrong target. You need to know original language.
> 0 votes

# Answer
No code needed, you can use Lingotek Module and trigger by rules module on new node save and or updated, condition: check in what language is uploaded so you can create another node in the second language. be carefull with google, it will penalize you if you index both nodes, to take care of this you can use No index module or something similar. I made a site with all of above and works perfect.
> 0 votes

# Answer
The error in the original post comes from addTranslation() itself:

```
  if (!isset($this->languages[$langcode]) || $this
    ->hasTranslation($langcode) || $this->languages[$langcode]
    ->isLocked()) {
    throw new \InvalidArgumentException("Invalid translation language ({$langcode}) specified.");
  }
  if ($this->languages[$this->defaultLangcode]
    ->isLocked()) {
    throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode}).");
  }

```

So your solution, adding the function `has_translation()`, amounts to doing some of the same checks that `addTranslation()` will do. An alternative is to catch the exception:

```
  try {
    $node->addTranslation($langcode, $node->toArray());
  }
  catch (\InvalidArgumentException $e) {
    // The translation already exists.
  }

```

I mean that `catch` clause literally: you can leave it out entirely or just put in a comment to reassure your future self that you did not forget something.
> 0 votes

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


# Question
Title: How to change the title of a modal window?
I have a link that displays a modal window.

The link redirects to a page view.

When I click on it, it is marked in the title of the modal window `Array`.

How to customize the title ?

```
<?php

namespace Drupal\commerce_agree_cgv\Plugin\Commerce\CheckoutPane;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the completion message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "agree_cgv",
 *   label = @Translation("Agree CGV"),
 *   default_step = "review",
 * )
 */
class AgreeCGV extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $store_name = $this->order->getStore()->getName();
    $store_id = $this->order->getStoreId();
    $pane_form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $attributes = [
      'attributes' => [
        'class' => 'use-ajax',
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => auto,
        ]),
      ],
    ];
    $link = Link::fromTextAndUrl(
      $this->t('the general terms and conditions of the store "@store_name"', ['@store_name' => $store_name]),
      Url::fromUri("internal:/store/$store_id/cgv", $attributes)
    )->toString();
    $pane_form['cgv'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept @cgv.', ['@cgv' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

}

```

# Answer
> 6 votes
mmmm if the above did not work

```
<a href="/some-thing" class="use-ajax" data-dialog-type="modal" data-dialog-options="{"width":700, "title":"YOURTITLE"}">LINK</a>

```

---
Tags: views, 8, theming, ajax
---


title: Deny access for Authenticated Users

text:
# Question
Title: Deny access for Authenticated Users
I'm using the moduke *Permissions by Term* and I love it. It works great and my complete system is now build around it. But I ran into a certain case and I am wondering if this is even possible.

I want a node to be visible for Anonymous users but not for a logged in user with a certain role.

Is it possible to do this. Is it possible to hide content or deny access for a certain role to content that is available for Anonymous users?

# Answer
If you give a permission to the `Authenticated User` role, you grant that permission to all other logged-in roles. It works like this because all logged-in users get that role.

However, as long as you don't grant a permission specifically to the `Authenticated User` role, you can pick and choose which individual logged-in roles to give the permission to. Then you can also give the permission to the `Anonymous User` role.
> 2 votes

---
Tags: 8, users
---


title: Alert message after add product

text:
# Question
Title: Alert message after add product
I am using Drupal 7 and the Commerce module.

How can I set the alert message after adding a product in Drupal Commerce.

# Answer
you need to use a callback in your submission .. something like this:

```
        YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'YourFormID') {
          $form['#submit'][] = 'custom_submit_function';
        }
}

        function custom_submit_function($form, &$form_state) {
          drupal_set_message('ALERT MSG HERE');
        }

```

this drupal\_set\_message() would give you the normal drupal message

if you don't know how to know your form ID ,, just print $form\_id inside **hook\_form\_alter()** you'll see it there so you can make your if condition depending on it.
> 0 votes

# Answer
In add product form, their will be a form\_id, use that to differentiate to display message in that form alone.

```
hook_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'custom_add_user_form'){
         $form['#submit'][] = 'custom_submit_handler';
    }
}

function custom_submit_handler(&$form, &$form_state){
   drupal_set_message('your message');
}

```
> 0 votes

# Answer
Or you could use the "Add to cart confirmation" module that was created for Commerce Kickstart 2 :)

https://www.drupal.org/project/commerce\_add\_to\_cart\_confirmation
> 0 votes

# Answer
If you are uncomfortable with writing custom code, I use commerce ajax add to cart for this functionality.

They provide installation instructions in the README.md file.

You can configure the pop up message through the UI @ `admin/commerce/config/ajax-cart`, and also customize it with css. There are also a couple of blocks created for a teaser to go in your top bar, and another cart display. There are a couple of little quirks, and i think some patches in the github repository for this module, but we use this module in production, and have had great results with it. There are a couple of other ajax add to cart modules for D7, but i found commerce ajax add to cart to be a great addition!
> 0 votes

---
Tags: commerce, status-messages
---


# Question
Title: Add '?' and '=' characters to query string
I'm trying to pass '?' and '=' symbols to a page using routing.yml

```
company.calc:
  path: '/form?company={nid}'
  defaults:
    _controller: FrameworkBundle:Redirect:redirect
    _title: 'Calc'
 requirements:
   _permission: 'access content'

```

but the symbols are transcoded to HTML-entities. It looks like `form%3Fcompany%3D%3Fcompany%3D18141` and leads to page 404.

Any ideas how to pass the string like

```
/form?company=1234

```

? This string is necessary to prepopulate the form's field.

Find the same question here but no reply, no solution :(.

# Answer
You declare query parameters in drupal routes in a mymodule.routing.yml file like this:

```
mymodule.mailcommitter:
  path: '/mailcheck/{uid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ProfilController::checkMailCommit'
    _title: 'commit mail'
  options:
      query:
        token: ""
  requirements:
    _permission: 'access content'

```

Then, you build an url by route like so

```
'url' => Url::fromRoute('mymodule.mailcommitter', ['uid' => 1], ['query' => ['token' => 'hello']])

```

Also check this doc: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes
> 13 votes

---
Tags: 8, routes
---


# Question
Title: How to Update db field value in hook_menu()?
I'm using Drupal 7, my requirement is to automatically update the node field value in a content type for a condition. I have used Hook\_menu() for to get a link and if i use that link my code will execute(In Cron). Below is my code,

hook\_menu():

```
function status_url_menu() {
$items = array();
$items['update_status'] = array(
'title' => 'Status Update',
'type' => MENU_NORMAL_ITEM,
'page callback' => 'update_status_url',
);

return $items;
}

```

And to fetch db table data i used db\_query()(I have few additional codes too but this is my core concept for my condition):

```
  function update_status_url(){
   $results2 = db_query('SELECT * FROM {field_data_field_status_tracker}');
   foreach($results2 AS $result2){
   $entity_id2 = $result2->entity_id;
   $in = 'Inactive';
   if($entity_id2==568){
        if($mydate2<$nowDate){  // Comparing current system date with my field
          db_query("UPDATE {field_data_field_status_tracker} SET field_status_tracker_value = $in WHERE entity_id = $entity_id2");

   }
  }
 }
}

```

I'm getting error in db\_query(update.. line

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Inactive' in 'field list'

```

And I also tried like this too:

```
$result2->my_field = $in;

```

No use i can't update my db field value, whether I'm using wrong method to update field value or please help me to rectify my problem. Thanks in advance... :)

# Answer
> 1 votes
I changed the code like this and it worked.

```
db_query("UPDATE {field_data_field_status_tracker} SET field_status_tracker_value = 'Inactive' WHERE entity_id = $entity_id2");

```

Thanks :)

---
Tags: nodes, database, hooks
---


# Question
Title: Paragraphs Entity Type Causing Issues After Core Update
I am getting this error whenever I try to create a node on Drupal 8.6.2.

> Drupal\Component\Plugin\Exception\PluginNotFoundException: The paragraph entity type does not exist. in Drupal\Core\Entity\EntityTypeManager line 133.

Right now, the paragraphs module is turned off. I have ran `drupal updb` to see if the database needed updating; nothing came back.

I tried `drupal moi` and `drupal mou` for paragraphs, but I get this error.

> \[ERROR\] Configuration objects (core.entity\_view\_mode.paragraph.preview) provided by paragraphs already exist in active configuration

How can I fix this error?

# Answer
I figured this out, not sure if it is the best way, I ended up using a mysql command to delete the config manually:

```
DELETE FROM `config` WHERE name='core.entity_view_mode.paragraph.preview';

```

After, you can enable and disable the module. Which appears to have fixed the issue.
> 5 votes

# Answer
Since you installed Drush, you can use the following command to delete the configuration object from the database.

```
drush cdel core.entity_view_mode.paragraph.preview

```
> 1 votes

---
Tags: 8, paragraphs
---


# Question
Title: Taxonomy term name as contextual filter for view
In D7 I was able to filter a view according to a taxonomy term **name** taken from the URL. An example would be this URL

```
http://www.gbyte.co/tags/drupal-planet/rss.xml

```

"drupal-planet" would be converted to the taxonomy term ID which then would filter the view results accordingly.

Now I have set up a corresponding D8 view with a contextual filter "Content: Tags (field\_tags)", field\_tags being the taxonomy field. However the D8 view will only show results when I pass the actual term ID into the URL like this:

```
http://www.gbyte.co/tags/9/rss.xml

```

I would like it to also work with the term **name** like D7 did. Is the functionality missing, or do I need to configure the view differently?

# Answer
Just for the sake of completion, at the time of writing the question I've managed to get around this issue by converting the taxonomy term name from the URL to a term ID in views\_hook\_pre\_view() and then using it as input for the contextual filter which accepts taxonomy IDs.

Here is the code for the views hook:

```
/**
 * Implements hook_views_pre_view().
 */
function my_module_views_pre_view(\Drupal\views\ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'blog' && $display_id == 'feed') {
    if (isset($args[0])) {
      $term = taxonomy_term_load_multiple_by_name($args[0], 'tags');
      if (empty($term)) {
        $term = taxonomy_term_load_multiple_by_name(str_replace("-", " ", $args[0]), 'tags');
      }
      if (!empty($term)) {
        $tid = key($term);
        $args[0] = $tid;
      }
    }
  }
}

```
> 4 votes

# Answer
The *Term name converted to Term ID* filter looks to be missing for D8 Views.

One site-builder workaround, is to add a **Relationship**, *Taxonomy terms on node* then to add a *Taxonomy Term: Name* filter to **Contextual Filters** using the aforementioned relationship. Checking the *Specify validation criteria* checkbox, set your **Validator** to *Taxonomy term name* & check the appropriate **Taxonomy** to filter on.
> 33 votes

# Answer
To expand on Shawn Conn's answer:

* Within the view config, under Advanced -\> Relationships click 'Add'
* Now select 'Taxonomy terms on node'
* On the next screen choose the 'tags' vocabulary and require the relationship.
* Now under Advanced -\> Contextual Filters click 'Add'
* Under 'When Filter is NOT available', choose 'Provide default value', 'Raw value from URL'. Select any other options appropriate to your needs.
* Under 'When Filter IS available or a default value is provided' choose 'Specify Validation Criteria' and select 'Taxonomy Term Name' for the validator. Choose the 'tags' vocabulary and then click apply.

Hope that helps!
> 8 votes

# Answer
@kiethm Has provided the correct way to approach this - Under the Contextual Filters you need to select **'Name'** and not **'Taxonomy Term ID'** then set your validation criteria to use **'Taxonomy Term Name'**.
> 3 votes

# Answer
I don't know if you still have this problem but I was able to create a relationship for "Taxonomy terms on node" using the desired taxonomy vocabulary and then create a contextual filter using that relationship for "Taxonomy term: Name" which allows you to validate based on name rather than TID.
> 2 votes

# Answer
I wrote a tiny module to restore the missing functionality and get this working properly again:

https://www.drupal.org/project/views\_taxonomy\_term\_name\_into\_id

It re-adds the 'Convert term name into ID' argument validator for taxonomy terms used in 'contextual filters' in Views. See the project page for more info and instructions.

Enjoy, -Derek (dww)
> 2 votes

# Answer
Hey I have been looking for this answer for a while. For anyone else like me looking for how to make it work, I Gumped my way into my into success partly from here and drupal.org's results and then also from following: http://redcrackle.com/blog/adding-contextual-filter-view-drupal-8

I'm using Drupal 8 and Zircon. I'm brand new so I may use the wrong terms. I wanted to make contextual image links in "Panel first col 1" based on the Category of the page that someone is on. What I did was go to Structure \> Views \> Carousel (the view that has the pictures in that block region) \> Advanced \> Add by Contextual Filters \> Has taxonomy term ID \> select in Provide default value: Taxonomy term ID from URL (which made no sense to me but whatever) \> then I checked all three boxes: Load default filter from term page, Load default filter from node page, that's good for related taxonomy blocks, Limit terms by vocabulary. Then for Vocabularies I checked Categories.

PHEW! Finally! Thanks to you all on here for pointing me in the right direction! I could not explain why it works, totally, but whatever, it does and I will keep being employed.
> 1 votes

# Answer
I have achieved this in Drupal-8 by taking contextual filter: of "Taxonomy term: Name"

Then Provide default value Type Taxonomy Term ID From Url

Then specifying the following validation criteria:
> 0 votes

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


# Question
Title: How to attach token in a custom form field
I have a custom form in Drupal 8. I need to attach tokens for fields of my form. Basically I want to add "Browse tokens" option for each field of my form.

# Answer
> 6 votes
`token.module` has various examples, for example this:

```
// Add the token tree UI.
$form['email']['token_tree'] = array(
  '#theme' => 'token_tree_link',
  '#token_types' => array('user'),
  '#show_restricted' => TRUE,
  '#weight' => 90,
);

```

This displays a link for tokens for the type user (and global tokens).

You can also use the `#element_validate` callback `token_element_validate` together with also adding `#token_types` to have it validated.

# Answer
> 4 votes
This is a copy from the "token.module".

```
function token_theme() {
  $info['token_tree_link'] = [
    'variables' => [
    'token_types' => [],
    'global_types' => TRUE,
    'click_insert' => TRUE,
    'show_restricted' => FALSE,
    'show_nested' => FALSE,
    'recursion_limit' => 3,
    'text' => NULL,
    'options' => [],
  ],
  'file' => 'token.pages.inc',
  ];

  return $info;
}

```

To avoid displaying the "global tokens" you need:

```
'global_types' => FALSE,

```

Code as a render element (don't forget the #(!)):

```
// Add the token tree UI.
$form['email']['token_tree'] = array(
 '#theme' => 'token_tree_link',
 '#token_types' => array('user'),
 '#show_restricted' => TRUE,
 '#global_types' => FALSE,
 '#weight' => 90,
);

```

# Answer
> 1 votes
```
$form['token_help'] = [
  '#theme' => 'token_tree_link',
  '#token_types' => ['user'],
];

```

https://www.drupal.org/documentation/modules/token

---
Tags: forms, 8, tokens
---


title: Alter an existing form

text:
# Question
Title: Alter an existing form
We just starting out with Drupal 8 and very quickly we ran into our first problem.

How should I alter an existing form in Drupal 8?

We need to alter the save method for the node form to do a redirect to an other page. We want to alter the node form to become something like a multistep form. After the user creates new content they get redirected to a new form (we created) to get some more information.

We solved our problem implementing `hook_entity_type_alter()`.

```
function mymodule_entity_type_alter(&$entity_info) {
  $handlers = $entity_info['node']->get('handlers');
  $handlers['form']['default'] =    'Drupal\mymodule\Form\MyExtendedNodeForm';
  $handlers['form']['edit'] = 'Drupal\mymodule\Form\MyExtendedNodeForm';
  $entity_info['node']->set('handlers', $handlers);
}

```

We then created a new form class that extends the node form and alter the save method.

```
class MyExtendedNodeForm extends NodeForm {

    public function save(array $form, FormStateInterface $form_state) {
      parent::save($form, $form_state);
      $node = $this->entity;
      $form_state->setRedirect('entity.regions.add_form', ['nid' => $node->id()]);
  }

}

```

This works perfectly, but is it good? If another module does the same, our code does not get executed anymore.

# Answer
I had to do the exact same thing yesterday, and I am still looking for a more Drupal 8 way to do this, but haven't found it. I ended up doing it this way:

```
<?php

/**
 * @file
 * This is my module.
 */

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Implements hook_form_alter().
 */
function MODULE_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_form') {
    $form['actions']['submit']['#submit'][] = '_MODULE_goto';
  }
}

/**
 * Make the form go to route.id.
 */
function _MODULE_goto($form, FormStateInterface $form_state) {
  $form_state->setRedirect('route.id');
}

```

I am still very interested in doing it a different way, my module looked so clean without the .module file :).
> 5 votes

# Answer
I'm using Drupal 8.1.1 and was trying to redirect users after they modified their account, i.e. clicking the Save button on the /user/edit page. I initially tried this:

```
/**
 * Implements hook_form_alter().
*/
function MODULE_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_form') {
    $form['#submit'][] = '_MODULE_goto';
  }
}

```

While that worked for the `user_login_form`, it would not work for `user_form`. For `user_form` I had to use

```
$form['actions']['submit']['#submit'][] = '_MODULE_goto';

```

I hope that helps others who stumble across the same problem!
> 4 votes

# Answer
Well I wanted to alter the `site_information_settings` form to add some fields.

As you, I had choice between

* `hook_form_alter` (or `hook_form_FORM_ID_alter`)
* extend the original form class

Wanted to make some OOP so I started writing a route subscriber service altering the `system.site_information_settings` route's `_form` attribute.

Then in my new class extending the `SiteInformationForm`, after the fields & their validators have been added and the submit function extended I felt exactly the same way as you... *Now what if another module rewrites the form's route as well to use its own class ?*

Back to the beginning, I had choice between two options... seems like I picked the wrong one.

`hook_form_alter` / `hook_form_FORM_ID_alter` seem to be the best way to alter an existing form.
> 2 votes

# Answer
After checking this issue, this is what I've found that should suit your case :

```
/**
 * Implements hook_entity_type_alter().
 */
function mymodule_entity_type_alter(&$entity_info) {
 $entity_info['node']->setFormClass('edit','Drupal\mymodule\Form\CustomNodeForm');
}

```
> 1 votes

# Answer
It looks like what you want to do, it not really to alter the save method, but to change the redirect when a node is saved.

In this situation, doing much like Drupal 7, `hook_form_alter` along with a custom submit handler (on the form or the button, depending on the form and requirement) would be a good solution.

What you describe in the question also works, but I would avoid overwriting the base class, unless I actually want to change something in the class.

The save method use just used as a submit handler anyways, so doesn't make much sense to overwrite just to add a redirect.
> 0 votes

# Answer
I think the better method is to still use one of the hooks from the form\_alter family, attached a submit handler, and within that set your redirect.

Contrib extending base classes to do this is hairy in my opinion. Especially since no function is changing, just redirecting.
> 0 votes

# Answer
You can create a new EventSubscriber which listens to the KernelEvents::REQUEST event, and then react when you are submitting a node form, something like this

Anyway the hook\_form\_alter way works ok.
> 0 votes

# Answer
What i found so far: Implementing a form alter hook and try to change the validate/submit handlers in the form alter hook itself only works if you change the $form\['#validate\]/ $form\[#submit'\] handlers. (calling form\_state functions for this wont work in the form alter hook itself)

But when you try this inside a validation handler, it tends to work:

```
// Load form submit handlers.
$submit_handlers = $form_state->getSubmitHandlers();

// Drop the core entity submitForm function.
$key_core_submit = array_search('::submitForm', $submit_handlers);
if ($key_core_submit !== FALSE) {
  unset($submit_handlers[$key_core_submit]);
  // Add your own submit handler.
  array_unshift($submit_handlers, 'yourmodule_submit_handler');
}
// Update submit handlers.
$form_state->setSubmitHandlers($submit_handlers);

```

This is because the form has now been built completely, not the case in the form alter hook itself.

The idea is: you can add a validation handler as the last one, evaluate other handlers that exist for the submit, and change them right there.

If you want to also change validation handlers, make sure yours runs prior to any other and change what you want in the validate handler.

Still searching for a better way myself, i just always need to replace the validate/submit handlers for the user register form. But other modules could exist that break my modules implementation. So my module would need to be able to check for these, and that's possible this way. I do wonder if some entity form after build function exists to pull this off. (something that runs when the form has been completed and is about to be delivered) (that's not way to complex for this simple case)

Bypassing the save() method's redirect is not possible, but unsetting the save() is via this way (+ implement your own). True, a class is nicer and offers easier access to objects/etc, but overriding a core class indeed leads to issues when other modules want to use these. That's not the case if you use this code.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: How do I create a route with a query string?
I have tried a few things and I cannot manage to make this working.

My route is the following.

```
    amu_hal.publicationsPerYear:
      path: '/publications/{year}'
      defaults:
        _controller: '\Drupal\amu_hal\Controller\AmuHalController::publicationPerYear'
        _title: 'publicationPerYear'
        year: 2016
        route_parameters:
          url: 'default'
      requirements:
        _permission: 'access content'

```

The code for the controller is the following.

```
    public function publicationPerYear($year,$url) {
      $url=urldecode($url);
      $url .='&fq=producedDateY_i:' . $year;

      try {
        $client = new Client();
        $response = $client->request('GET', $url);
        $content = json_decode($response->getBody(), true);
        // ...
      }
    }

```

The request http://mysite/publications/2016?url=https%3A%2F%2FmyWS%2Fsearch%2F%3Frows%3D5%26sort%3DproducedDate\_tdate%2Bdesc%26fl%3Dtitle\_s%2Cen\_title\_s%2Clabel\_s%2Cen\_label\_s%2CdocType\_s%2CauthIdHal\_s%2ChalId\_s%2CstructId\_i%2Curi\_s%2Ckeyword\_s%2Cen\_keyword\_s%2CauthLastNameFirstName\_s%2CjournalTitle\_s%26fq%3DauthFullName\_t%3A(%22M%22+OR+%22e+d%22) gives the following error:

> RuntimeException: Controller "Drupal\amu\_hal\Controller\AmuHalController::publicationPerYear()" requires that you provide a value for the "$url" argument (because there is no default value or because there is a non optional argument after this one). in Drupal\Core\Controller\ControllerResolver-\>doGetArguments() (line 165 of /var/aegir/platforms/drupal8-dev/core/lib/Drupal/Core/Controller/ControllerResolver.php).

# Answer
You cannot create a route based on the query string, but you still can retrieve query string values in your code:

```
amu_hal.publicationsPerYear:
  path: '/publications/{year}'
  defaults:
    _controller: '\Drupal\amu_hal\Controller\AmuHalController::publicationPerYear'
    _title: 'publicationPerYear'
    year: 2016
  requirements:
    _permission: 'access content'

```

```
public function publicationPerYear($year) {
  $url = \Drupal::request()->query->get('url') ?: 'default';
}

```
> 9 votes

# Answer
Meanwhile (Drupal 8.6) it's possible to declare query parameters in drupal routes. In a mymodule.routing.yml file, to declare a query variable "token", do it like this:

```
mymodule.mailcommitter:
  path: '/mailcheck/{uid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ProfilController::checkMailCommit'
    _title: 'commit mail'
  options:
      query:
        token: ""
  requirements:
    _permission: 'access content'

```

Then, you build an url by route like so

```
'url' => Url::fromRoute('mymodule.mailcommitter', ['uid' => 1], ['query' => ['token' => 'hello']])

```

The result is an uri like `/mailcheck/1/?token=hello`

Also check this doc: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes
> 9 votes

# Answer
I don't think we support passing a query argument through like that.

Just get the request object with `Request $request` and then get the url from there with `$request->query->get('url');`

---

### Sample method

```
  /**
   * @param \Symfony\Component\HttpFoundation\Request $request
   */
  public function download(Request $request) {
    dd($request->query->get('url'));
  }

```
> 5 votes

---
Tags: 8, routes
---


title: Entity relation field view

text:
# Question
Title: Entity relation field view
I have a D8 entity reference field question. I have 3 content types: Student, Class, Book.

A student can have several classes and a class can have several books. I have in student an entity reference field of type content connected to classes. I have in class an entity reference field connected to books.

In a view (block student class book) I want to show the student name, his/her classes and the books associated with each class.

I am able to create a view showing the student and it's classes (using the relationships option in a advance) but the books are not showing up!

Please can somebody help? Thanks

# Answer
> 1 votes
If you don't need to have filters or sorting or other view related things interacting with books or classes then I would set the view up to not display fields and use relationships, etc. Rather I'd configure it to display a view mode of the Student. Then do all display configuration for what should appear about the student in that view mode. I find using view modes, vs configuring fields directly in the view, to be an easier way to configure views in most scenarios. Plus if you need to display the same information somewhere else, it's much easier to re-use the view mode vs having to re-configure a view.

In your view, instead of showing fields, show `Content` and then choose a view mode of your Student. (You can create new view modes at `/admin/structure/display-modes/view` or Manage \> Structure \> Display Modes \> View Modes in the admin menu.)

Then update your Student view mode via the manage display to show whatever student content plus the classes field. Configure your classes field to, again, show a particular view mode.

Then update your Classes view mode to show whatever content you want to display about the class plus the books field (not sure if you'd want to show just the label or again another view mode).

---
Tags: views, 8, nodes
---


# Question
Title: How to get all values of particular custom field of user entity using EnitityQuery?
I have added one custom field to user entity called as "customer\_no".

On User Registration Form, I want to check whether customer\_no already exists.

For that, now I want to Fetch all user's values of customer\_no.

I tried below code but it is not working:

```
if(isset($cust_no)) {
    $ids = \Drupal::entityQuery('user')
      ->condition('field_customer_number_reseller_i','','<>')
      ->execute();
    $users = User::loadMultiple($ids);
    print_r($users); exit;
  }

```

Please Help me over here.

# Answer
> 1 votes
You could add a `UniqueField` constraint:

```
/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function mymodule_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'user' && isset($fields['field_example'])) {
    $fields['field_example']->addConstraint('UniqueField');
  }
}

```

Which executes the entity query for you, see UniqueFieldValueValidator::validate().

---
Tags: entities, users, forms
---


# Question
Title: How can I remove the remains of the Mass Contact module not properly uninstalled?
I tried the Drupal 8 version of the Mass Contact module (8.x-1.0-beta2, released on June 2017).

As I was not fully satisfied, I decided to uninstall it.
Once done, I got errors when I tried editing a user account.

> The website encountered an unexpected error. Please try again later.
> Error: Call to undefined function `mass_contact_opt_out_allowed_values_callback()` in `options_allowed_values()` (line 89 of core/modules/options/options.module).

Digging a little bit, I found that the code to uninstall the module was not fully implemented: it leaves (at least) two configurations (*field.field.user.user.mass\_contact\_opt\_out* and *field.storage.user.mass\_contact\_opt\_out*) and a table in the database (*d8\_user\__mass\_contact\_opt\_out*).

How can I get rid of that and have a clean uninstall?

# Answer
> 2 votes
This is an issue already resolved for the 8.x-1.x branch, as reported in Uninstall should remove mass\_contact\_opt\_out field.

The code that has been added to the uninstall hook is the following one.

```
Drupal::configFactory()->getEditable('field.field.user.user.mass_contact_opt_out')->delete();
Drupal::configFactory()->getEditable('field.storage.user.mass_contact_opt_out')->delete();

```

If you have Drush installed, you can write those two lines in a file (for example, fix-module.php) and run it with `drush php-script fix.module.php`. You can also put the following code in a file next to the authorize.php file that comes with Drupal core, and access that file from the browser.

```
use Drupal\Core\DrupalKernel;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

// Change the directory to the Drupal root.
chdir('..');
$autoloader = (require_once 'autoload.php');

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->boot();
  Drupal::configFactory()->getEditable('field.field.user.user.mass_contact_opt_out')->delete();
    Drupal::configFactory()->getEditable('field.storage.user.mass_contact_opt_out')->delete();
} catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

```

# Answer
> 1 votes
Yes, this function is defined in configuration. You should find all occurrences of the function name by a full text search of the exported configuration:

*field.storage.user.field\_example.yml:*

```
  allowed_values_function: 'examplemodule_allowed_values_callback'

```

More info How do I programmatically update the allowed values of a list field?

Then you can either remove the function name from the field config (in case you want to keep the field data) or remove the field config and field storage yaml files to delete the field data on the next config import. If you have still configured the field in display modes, you get an error when importing, then remove all references of the field in the config files mentioned in the error message.

---
Tags: 8
---


title: Moving module location

text:
# Question
Title: Moving module location
I have a test module located under site/all/modules/custom. First, I did uninstalled the module, cleared cache. then , I did moved the test module to modules/custom folder which is a new location to put Drupal 8 module.

After that, I have enabled the test module, then Clear All Caches. Now, Drupal 8 keeps says can not find the test module under old location (site/all/modules/custom).

I thought Drupal 8 probably stored path in a DB table, but i am unable to find the table. Can any one tell a solution about How to fix above problem?

# Answer
You can do this without uninstalling, but it takes some fiddling:

1. Move the module in filesystem
2. invoke `drush ev "drupal_flush_all_caches();"`
3. invoke `drush cr`

The crucial setting is the entry `system.module.files` in `key_value` database table. If you move the module(s), the try to run `drush cr` directly, it may fail because drush tries a full bootstrap and fails to locate the required files.

`drush ev` does an error-free bootstrap using drush\_bootstrap\_max(), and `drupal_flush_all_caches` rebuilds `system.module.files` config without trying (and failing) to load the moved files. Whereas `drush cr` does a full-site bootstrap, which causes drush to halt on any errors.
> 27 votes

# Answer
I had the same problem promoting a module from `custom` to `contrib`. The key for me was clearing the (APC) autoloader cache in combination with the Drupal cache.

I think I ended up with uninstalling the module, `drush cr`, and then forcing an autoloader cache invalidation (by sticking this file in the webroot and pointing the browser to it):

`<?php
apc_clear_cache();`

following by another `drush cr` for good measure, and then finally reenabling the module.

Here's some background from Pantheon about the APC: https://pantheon.io/docs/alternative-php-cache/
> 10 votes

# Answer
You can add To your settings.local.php

```
$settings['deployment_identifier'] = 'ANY CUSTOM STRING';

```

this is used by acquia/blt to clear the container cache. According to the blt documentation in code:

```
/**
 * Deployment identifier.
 *
 * Drupal's dependency injection container will be automatically invalidated and
 * rebuilt when the Drupal core version changes. When updating contributed or
 * custom code that changes the container, changing this identifier will also
 * allow the container to be invalidated as soon as code is deployed.
 */

```
> 8 votes

# Answer
You don't need to re-install, a cache clear after moving a module should be enough. If not, then you might not actually have cleared the caches?
> 7 votes

# Answer
this added to local.settings.php did the trick for me:

```
   /**
 * Class Loader.
 *
 * If the APC extension is detected, the Symfony APC class loader is used for
 * performance reasons. Detection can be prevented by setting
 * class_loader_auto_detect to false, as in the example below.
 */
$settings['class_loader_auto_detect'] = FALSE;

```

i guess restart the server or empty apc cache would have done the trick too
> 6 votes

# Answer
Paths are more a matter of registry than cache. Thus, I would recommend to rebuild the registry with the Devel module or with Drush.

What I did in Drupal 7 was to truncate the registry database tables with PHPMyAdmin.
> 1 votes

# Answer
Tried the above and nothing seemed to work for me. In the end I went into the database for my D8 site and truncated all the tables starting with 'cache\_' and that did the trick - perhaps this will help someone else.
> 1 votes

# Answer
ahebrank's answer of creating a php file in the root of your Drupal instance to clear the APC cache is the least invasive method I've found to achieve this since it only affects that Drupal instance.

Another option is to restart Apache followed by drush cr, which has the same result but obviously has an impact on any other sites on the same server.

In my case, I needed to move all of the contrib modules in my Drupal instance from modules/ into modules/contrib/. This resulted in a 500 error on my site. I don't know which module caused the 500 error, but it wasn't practical to uninstall and reinstall all of my modules.
> 1 votes

# Answer
I would try uninstalling the module before moving it.

Just put the module back in it's original location and uninstall it with "drush pm-uninstall" or by using the "Uninstall" tab on the "Extend" page in the admin UI. You *should* be able to move it after these steps.

* Option 2:

Too lazy to look it up on the workstation, if D8 is like D7 you will have a system table in the database with an entry for your module, you can just delete the entry where name="yourModuleName" and re-install your module.
> -2 votes

---
Tags: 8
---


# Question
Title: Override contrib Disqus behavior settings
I want to override a contrib module's library setting that is being attached to page using `hook_js_settings_alter()`. But, I am unable to change the `setting` that is being called in js.

Here is the code that is being called in Disqus module Element:

```
$element['#attached']['library'][] = 'disqus/disqus';
$element['#attached']['drupalSettings']['disqus'] = $disqus;

```

I want to override settings in `$disqus` that is being called in Disqus.js

```
Drupal.behaviors.disqus = {
  attach: function (context, settings) {
    // Load the Disqus comments.
    if (settings.disqus || false) {

```

I could override this element with `hook_element_info_alter`, but is there a way to override the above `settings.disqus` using other hooks.

# Answer
You can also use `hook_js_settings_alter` Something like:

```
/**
 * Implements hook_js_settings_alter().
 */
function YOURMODULE_js_settings_alter(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  if (isset($settings['disqus'])){
    // Change settings here
    $new_disqus_settings = [];
    $settings['disqus'] = $new_disqus_settings;
  }
}

```
> 1 votes

---
Tags: 8, javascript
---


# Question
Title: How do I enable a module by exporting the configuration?
I enabled these core modules: Language, Content translation, Config translation, and Interface translation. I exported the core.extensions.yml file, but when I placed the same file in the development environment, those modules weren't installed.

How can I install modules by exporting the configuration?

# Answer
You need to import the configuration from the file, into the database. Configuration files are only a backup to configuration. The active configuration is in the database.

You can import configuration at `/admin/config/development/configuration` or run `drush cim`.
> 3 votes

# Answer
You have to import the configuration files after you export them. Either from the UI by going to *configuration \> configuration sync*. Or using `drush cim -y` or `drush csim -y` if you were using config split.
> 0 votes

---
Tags: 8, importing-exporting, configuration
---


# Question
Title: Conditional fields on content type with paragraphs
I saw this question repeat in a few places without an adequate answer.

I have a D8 site that has a certain contain type ('deals') which contains an array of 'deal' paragraphs. Each 'deal' contains a 'deal\_type' field and then a few content fields ('image', 'text', 'banner', etc.).

I would like to conditionally show the paragraph fields, according to what the user selected in the 'deal\_type' dropdown.

I saw some answers mention a `MODULE_form_alter()` hook but this didn't seem to be called when I load my 'edit content type' page.

Can anyone help with this?

# Answer
Yes you will have to hook form alter. Make sure that you have done the following to make sure it's working. 1- create a module say it's called deals 2- add the deals\_form\_alter(...add the default params here ) In the deals.module file. 3- clear the cache 4- add your edit form is in an if condition then right the following logic. (You can get the form is by dumping the $form\['#id'\]. 5- use the states functionality or Ajax callback to hide and show the fields you want.

https://www.drupal.org/docs/8/api/form-api/conditional-form-fields And https://www.drupal.org/docs/8/api/javascript-api/ajax-forms
> 0 votes

---
Tags: 8, forms, paragraphs
---


title: Get the user's current language code

text:
# Question
Title: Get the user's current language code
How can I get the user's current language code in a view as a raw value, for example *en* or *fr-ca*?

This isn't for filtering content. I need the raw value of the users' current language to pass into a URL for a third-party tool. I added a custom text field. Then placed in some Twig code. The code is just failing to the fallback `else` value.

Based on other forum posts, I tried this code.

```
{% if language.getId() == 'en' %}
  en
{% elseif language.getId() == 'es-us' %}
  es-us
{% elseif language.getId() == 'en-us' %}
  en-us
{% else %}
  failed
{% endif %}

```

I get *failed*.

```
{% if language == 'en' %}
  en
{% elseif language == 'es-us' %}
  es-us
{% elseif language == 'en-us' %}
  en-us
{% else %}
  failed
{% endif %}

```

I still get *failed*.

```
{% if language.id() == 'en' %}
  en
{% elseif language.id() == 'es-us' %}
  es-us
{% elseif language.id() == 'en-us' %}
  en-us
{% else %}
  failed
{% endif %}

```

I still get the same output.

# Answer
> 0 votes
I would suggest adding a custom text field then add the language value as a field. this way you will have the language as a replacement pattern that you can use with any custom link field which would be something like {{ language }}

You need to checkout the style settings of to use the custom link option.

---
Tags: views, 8, tokens
---


# Question
Title: Display order of entity reference fields
I have an entity reference field which references and displays multiple nodes on a Drupal 7 install.
I am trying to get them to display in date order (the date is a field on the referenced nodes). The problem I have is that if a referenced node date is changed, or a new one created, the display order doesn't change.

I use a entity reference view to order the nodes on their date fields, which works when you manually edit the master node and then save it. This then updates the order. However this not a very practical solution.

I have tried creating a module which when referenced nodes are modified or created, it programatically loads and saves the master node using node\_load and node\_save.

However this doesn't trigger the referenced nodes to update their display order.

Does anyone know anything else I can try?

# Answer
> 1 votes
In case someone stuck on this, i have a solution for Drupal 8 (you can figure it out for 7):
In `themename.theme` add a preprocess funtion:

```
function themename_preprocess_field__field_entity_reference(&$variables) {
    usort($variables['items'], function ($a, $b) {
        $a = isset($a['content']['#node']) ? $a['content']['#node']->field_display_order->value : null;
        $b = isset($b['content']['#node']) ? $b['content']['#node']->field_display_order->value : null;

        // Do the comparison
        // This <=> operator only work for PHP >= 7
        return $a <=> $b;
    });
}

```

# Answer
> 0 votes
1. Go to `Structure > Content types` and select your content type.
2. Click the "Manage Fields" tab.
3. Click `edit` next to your entity reference field.

There should be a "FIELD SETTINGS" area with an "ENTITY SELECTION" box. At the bottom of the "ENTITY SELECTION" box, there's a "Sort by" drop-down menu that should let you select "A field attached to this entity." That should give you access to the date field that you want to use as your sort value.

---
Tags: 7, entities
---


# Question
Title: Ajax callback is not working on views exposed filters
I am implementing dependent filters in views exposed filter for content:datasource search(Solr search). I have a requirement that in exposed dropdown field when a category is selected, by ajax i need to fetch the sub-categories and show up in another dropdown.For this I tried like below but its not going to callback function only. There is nothing logging in the network console also. Can anyone help me here to resolve.

```
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

function module_form_alter(&$form, &$form_state, $form_id) {
$form['field_categories']['#ajax'] = array(
        'callback' => 'module_get_subcategories',
        // 'callback' => '::module_get_subcategories',
        'event' => 'change',
        'wrapper' => 'edit-field-subcategory',
        'progress' => array(
          'type' => 'throbber',
          'message' => NULL,
        ),
      );
}

function module_get_subcategories(&$form, FormStateInterface $form_state) {
   $response = new AjaxResponse();
   $message = 'test';
   $response->addCommand(new HtmlCommand('#edit-field-subcategory', $message));
   return $response;
}

```

# Answer
Something is weird in the code, What is that return statement in the last two lines?

For the ajax, try using `$form['field_categories']['widget']['#ajax']`

Make sure that you have cleared the cache too and that your module is actually called module.
> 0 votes

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


# Question
Title: Can't sync site config from git, entities exist of type x
For whatever reason I seem unable to find a good resource to explain syncing the actual structure of a site (like blocks and configs).
I'm using git currently and am doing local development using lando. I have just been using the same folder this whole time but recently had to do some things and needed to clone my repo.
I've got the site running but it's back to the "defualt" state and made me install drupal and such.

I have the `config/sync` folder but cannot use `drush cim` or sync via the UI.

```
The configuration cannot be imported because it failed validation for the following reasons:
Entities exist of type Taxonomy term and Vocabulary Blog Categories. These entities need to be deleted before importing.
Entities exist of type Shortcut link and Shortcut set Default. These entities need to be deleted before importing.
Entities exist of type Paragraph and Paragraph type Webform + Content. These entities need to be deleted before importing.
Entities exist of type Paragraph and Paragraph type Standard Content. These entities need to be deleted before importing.
Entities exist of type Content and Content type Page. These entities need to be deleted before importing.
Entities exist of type Content and Content type Homepage. These entities need to be deleted before importing.
Unable to install the Commerce Store module since it requires the Path alias module.
Unable to install the Commerce Number Pattern module since it requires the Path alias module.
Unable to install the Commerce Order module since it requires the Path alias module.
Unable to install the Commerce Product module since it requires the Path alias module.
Unable to install the Commerce Cart module since it requires the Path alias module.
Unable to install the Commerce Checkout module since it requires the Path alias module.
Unable to uninstall the Path alias module since the Path module is installed.
Unable to uninstall the Path alias module since the Pathauto module is installed.

```

This is spat out by the UI.
I had tried to do something with the `uuid` but it obviously didn't work. I'll say that's because, again, I can't seem to find a good explanation of how this actually works.

# Answer
Two things are happening:

1. In your active configuration in the database, some module(s) is/are installed, that isn't/aren't installed in the configuration you are trying to import. The problem is that you have content for the thing(s) being uninstalled, so if you were to import the configuration, you'd have ghosts in your database. These ghosts are listed in the errors that begin with 'Entities exist of of type X'.

To resolve this you'll need to either enable the missing item(s) in the configuration you're trying to import, or you'll need to delete the items from the database before you import your configuration.
2. The configuration you are trying to import has enabled modules, but the codebase for those modules does not exist in the Drupal installation you are trying to import the configuration into. These modules are listed at the end of the errors that begin with 'Unable to install the X module' (ex - you are missing the Path Alias code base).

To resolve this, you'll either need to add the code for the required modules to your codebase.
> 2 votes

---
Tags: 8, configuration
---