# Question
Title: How to reset admin password if account is blocked
I am using Drupal 8 and I forgot my admin password and have it blocked due to trying to login unsuccessfully 5 times. I am running my website in localhost.

How can I reset it? Is it possible to do with a SQL query?

# Answer
> 5 votes
Drush is ideal but if you don't have that installed, you'll need to do more than just a sql query because you'll need to get a hash of the password you want to use.

First find your core drupal main directory and run

```
php core/scripts/password-hash.sh "your_new_password"

```

In phpmyadmin or your sql db manager of choice find the admin user in users\_field\_data and replace the pass value with the hash you got from the command above.

Then truncate the 'cache\_entity' table. If you were locked out from too many failed login requests also delete instances of your IP in the 'flood' table.

Then you should be able to log in with your new password.

# Answer
> 1 votes
with drush installed you can probably do

```
drush upwd USERNAME --password="SOMEPASSWORD"

```

---
Tags: 8, users
---


# Question
Title: Building a simple render array and rendering it
I'm trying to render a render array. This render array will be configurable through a UI.

For some reason, I'm unable to render it.

I've isolated the issue so we can replicate it quickly.

Here's the render array:

```
$render_array = array(
  '#type' => 'html_tag',
  '#tag' => 'h1',
  '#attributes' => array('class' => 'title'),
  'children' => array(
    array(
      '#type' => 'link',
      '#title' => 'Link title',
      '#href' => 'Link URL',
      '#attributes' => array('class' => 'inner'),
    )
  )
);

$html = render($render_array);

debug($html);

```

The result of this is:

```
<h1 class="title" />

```

I tried many possibilities, tested multiple things... but it won't work.

I also searched the API and found this comment and the example in the comment is pretty much the same as mine... but it won't work either.

Is there an easy why to build a complete HTML structure with a render array ?

I could use `'#theme' => 'link'` but it's not advised, see this thread.

Anyone got a clue ?

Thanks!

Edit1: I opened an issue on Drupal.org which is a workaround to get this fixed.

# Answer
I believe "children" needs to have a "#" ... You could also try using #value instead of children
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Sort grouping field associated with taxonomy term by weight
I'm currently trying to figure out how I can sort the grouping fields(Taxonomy Term) by weight that I have setup on my views.

As shown in this screenshot below I have a grouping field that is associated with a taxonomy term.

1. Application Deadline
2. Scholarship Deadline
3. Class Dates

The only problem is that, it is not sorted accordingly by weight.

Is there a way I could the taxonomy terms by weight. I tried configuring the views but I can't seem to find the solution in solving my problem.

# Answer
> 0 votes
I had to manually move the terms to a new order for the weights to change from a default 0 (you can click "show row weights" on the taxonomy page to see that they have changed after dragging out of order and then back into order; you only need to do this with one term to apply to all terms within a given level).

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


# Question
Title: D8 Prepopulate webform full_address value field from url?
I am able to prepopulate the name, date, body etc they are single value elements. The full\_address.value field wont accept the address city state value in the url. from views rewrite link I have tried full\_address.value (changes to full\_address\_value in url), full\_address by itself and full\_address-value. None of those work. I see the value in the url however, it doesn't prepopulate the full\_address.value element. Ideas? Syntax issue in rewrite?

# Answer
> 1 votes
Thru trial and error I made the composite element full\_address prepopulate using &full\_address\[value\]= {{ field\_address }} as the receiving field/element name. putting the brackets in made it work. Ahhh...

---
Tags: 8, webforms
---


# Question
Title: Trying to print translated field label/values to twig
I have been trying to figure out how I can print or display the translated values based on the current language of the page.

I have tried using some of the following options `{% trans %}` and `{% endtrans %}` does not work

```
{# {% trans  %}
<li class="tab">{{ tab_label.entity.field_tab_title_selection.value }}</li>
{% endtrans %} #}

```

---

2nd Option using preprocess, the problem with this method in the event I have multiple language setup I have to create multiple if's statement. Lets say I have 10 languages then I have to create 10 conditions

**Using Pre-process**

```
function iom_preprocess_page(&$variables) {

    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $vars['language'] = $language;

}

```

---

```
{# {% if (language.getId() == 'fr')  %}

<li class="tab">{{ tab_label.entity.field_tab_title.entity.translation('fr').label }}</li>

{% else %}

<li class="tab">{{ tab_label.entity.field_tab_title.entity.label }}</li>

{% endif %} #}

```

# Answer
First the {{ trans }} and {{ var|t }} methods only do substitutions from the UI language strings (e.g. specific strings (e.g. "More") that have translations defined (in the UI or code). So, this will not work for 'random' text entered into a field.

That said, it looks like tab\_label is an entity reference field. So, tab\_label.entity will always get the default language entity.

I would say do the `theme_preprocess_xxx` to add the current language to what you are rendering (e.g. if it's a block or a node use those, not just page. Preprocess variables may or may not trickle down. I'd only pass on the langcode just to save a bit of memory. So the preprocess function would look like:

```
function theme_preprocess_XXX(&$variables) {
    $language = \Drupal::languageManager()->getCurrentLanguage();
    $variables['lang_code'] = $language->getId();
}

```

Next in the twig file, you can use this code to get the translations:

```
{% if tab_label.entity.hastranslation(lang_code) %}
  {% set tabLabel = tab_label.entity.translation(lang_code).field_tab_title.entity.label %}
{% else %}
  {% set tabLabel =tab_label.entity.field_tab_title.entity.label %}
{% endif %}
<li class='tab'>{{ tabLabel }}</li>

```

Using the set will help keep your HTML easy to validate in the template.
> 2 votes

---
Tags: theming, entities, i18n-l10n
---


title: CORS setup with ReactJS Fetch API

text:
# Question
Title: CORS setup with ReactJS Fetch API
I have a ReactJS app that fetches an external API URL with the following structure.

```
fetch(url) // or fetch(url, {mode:'cors'})
  .then(response => response.json())
  .then(data => {

```

In my browser, when it tries to render the component, I am getting the following error message

> Failed to load https://XXXXX/jsondata: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So I research how to enable CORS in Drupal 8 and doing trial and error for different configurations didn't work.

This is my current `cors.config` under `services.yml` file

```
  cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with', 'access-control-allow-origin','x-allowed-header','*']
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: ['*'] // or ['POST', 'GET', 'OPTIONS', 'DELETE', 'PUT', 'PATCH']
    # Configure requests allowed from specific origins.
    allowedOrigins: ['https://XXXX/','*']
    # Sets the Access-Control-Expose-Headers header.
    exposedHeaders: true // or false
    # Sets the Access-Control-Max-Age header.
    maxAge: false // or 1000
    # Sets the Access-Control-Allow-Credentials header.
    supportsCredentials: true // or false

```

I have tried to install a Chrome extension that is amazing that removes this error but of course this will only be working in my device.

Im not entirely sure but is this something to change Drupal CORS config or allowing `Access-Control-Allow-Origin` on the API URL side (https://XXXX)?

# Answer
> 1 votes
I would just like to answer my own question. After reading more documentation about how CORS works, I found out that, to allow Drupal access other site/server, CORS must be enabled in the other party not in Drupal site itself. Some basic explanation found here too. https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work/10636765#10636765

---
Tags: 8, javascript
---


title: Import always show changes

text:
# Question
Title: Import always show changes
I have problem with import/export. After import it always says that there is changes after sync.

Anyone faced this issues? How to fix it (showing no changes after import all)?

# Answer
I found myself problem. Export full create different .yml file than export single. That why it make some fields lost. Besides, the export function might ignore hidden fields in .yml files. In this case it should add fields manually to avoid conflict.
> 0 votes

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


title: Check a revision exists for a node

text:
# Question
Title: Check a revision exists for a node
How do I check there is a revision exists for a node? I can load the node details using the following code.

```
$nid = "my_node_id";
$node_details = \Drupal\node\Entity\Node::load($nid);

```

How do I check if there is a revision for a node? Putting it differently: How can I get the revision ID of a node after creating a new revision?

I create a new revision using this code.

```
  $original_revision = \Drupal\node\Entity\Node::load($nid);
  $original_revision->my_field_to_be_modified= "my_value";
  $original_revision->setNewRevision(TRUE);
  $original_revision->setRevisionCreationTime($time_stamp);
  $original_revision->save();

```

# Answer
Use `getRevisionId();` The revision identifier of the entity, or NULL if the entity does not have a revision identifier.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21RevisionableInterface.php/function/RevisionableInterface%3A%3AgetRevisionId/8.2.x
> 1 votes

# Answer
alter way query form database and check $count if 1 mean it exists else 0

```
$count = \Drupal::database()
        ->select('node_revision')
        ->condition('vid', {revision_number})
        ->countQuery()->execute()->fetchField();

```
> 0 votes

---
Tags: nodes
---


# Question
Title: How do I display a link icon in custom modules?
I would like to display an icon of correct answer but in my condition full URL is displaying (it's not displaying icon ) how I'll manage. This icon will be on a table so the user can click that icon and check the answer. please guide me where I'm doing wrong. here I have put some linking portion of my code. I'm writing custom modules in drupal 8. Thanks

```
$imgsrc = $base_url.'/scp/sites/default/files/images/corr_icon.gif';
$correct_link = Url::fromUserInput('/answer/'.base64_encode($data->ans_refno).'by'.base64_encode($data->q_id));
'isanswer' => \Drupal::l($imgsrc, $correct_link),

```

# Answer
You can convert markup with image tags and convert it into URL with image like below:

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

$imgsrc = Markup::create("<img src ='$base_url/scp/sites/default/files/images/corr_icon.gif'>");
$correct_link = Url::fromUserInput('/answer/'.base64_encode($data->ans_refno).'by'.base64_encode($data->q_id));
'isanswer' => \Drupal::l($imgsrc, $correct_link),

```
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: How to progragrammatically get NodeType translated value in D8?
Fetching node translation

```
$node = Node::load($nid);
$node->getTitle(); // returns title in en(default language).
$translated_node = \Drupal::service('entity.repository')->getTranslationFromContext($node, 'es');
$translated_node->getTitle(); // Returns translated title in es (spanish).

```

If we want to fetch the bundle's translation. The above approach doesn't work.

Kindly advise?

```
$article = $node->bundle();
$article->label(); // returns "Article".
$translated = \Drupal::service('entity.repository')->getTranslationFromContext($article, 'es');
$translated->label(); // Also returns "Article".

```

Translation for bundles provided from `/admin/structure/types/manage/article/translate/es/edit`

# Answer
You need to set the config override language to the desired language:

```
  $language = $language_manager->getLanguage('es');
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);

  // Load the node type here.

  $language_manager->setConfigOverrideLanguage($original_language);

```

Taken from `user_mail()`
> 5 votes

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


title: How can I log(watchdog)?

text:
# Question
Title: How can I log(watchdog)?
In D7 is used to log using Watchdog function. In D8, I see its gone and I should use something called the logging API.

What I a trying to do:

1. I have created a menu/route, `mysite.com/logmessage`
2. When user opens that url in browser, I want to log "hello" to the dblog.

Where should I register the service that D8 documentation says to do? Is it in the services.yml file in `sites/default` folder?

Can I just load the said class in my controller/module file and call the function for logging? Or should I explicitly extend the class first in my module before using the function?

# Answer
> Can I just load the said class in my controller/module file and call the function for logging?

Yes; well, by "load the said class" you actually mean "get or inject an instance of the service class" in this context, but yes.

> should I explicitly extend the class first in my module before using the function?

Not unless you need functionality that the existing service doesn't provide.

In non DI code use:

```
\Drupal::logger('my_module')->info('Info');

```

In DI code, inject the service and use:

```
$this->logger->info('Info');

```
> 8 votes

# Answer
There are many different types of logging, all called the same way as per the documentation:

```
\Drupal::logger('my_module')->alert($message);

\Drupal::logger('my_module')->info($message);

\Drupal::logger('my_module')->debug($message);

```

Just call this code anywhere in your module, if you want to register `logmessage` as a path you'll need to create `my_module.routing.yml`, etc.
> 4 votes

---
Tags: 8, log-messages, symfony-services
---


# Question
Title: Webform what is format required to prepopulate datetime element
Sending default date format (medium) from VIEW rewrite results link, URL adding ?apptdatet={{ field\_apptdatet }} This never fills the webform datetime field. The value is shown in the url as medium formatted date. day mm dd yyyy hh:mm:ss On the webform the apptdatet field shows the correct format mm/dd/yyyy hh:mm:ss, the value is always blank however. in the view apptdatet shows as Mon 05-14-2018 15:30 Does anyone know what Webform is looking for?

# Answer
> 3 votes
You need to use an ISO date.

```
?apptdate=2018-06-13T01:01:01-0400

```

---
Tags: 8, webforms
---


# Question
Title: "You need to be logged in to view that page" alert for authenticated user
I have created a page using hook\_menu for "employee" role using the code below:

```
 $items['admin/employee'] = array(
    'title' => 'Dashboard - Employee',
    'page callback' => 'employee_page',
    'access arguments' => array('Access administration theme'),
    'type' => MENU_NORMAL_ITEM,
);

```

When this page is viewed by an employee this alert appears: "You need to be logged in to view that page".

I tried to rebuild cache etc.

PS. I don't have an issue to access this page as an admin. Maybe I should use different access arguments?

# Answer
First off, checking access as user 1 or Administrator is not a test because no permission checks are done for user 1, and in most cases Administrators have all permissions.

Two, your permission is mixed case, change it to all lower case and clear the cache.

Three, in order to access anything under `/admin`, user will also need `access administration pages` permission as well - or whatever permission is assigned on that menu item (I think that’s the one).
> 1 votes

---
Tags: users
---


# Question
Title: EntityQuery how to get all delta and good for field_dates
I've got these dates linked to a node.

I just want to make a request to render all node when `time()` is between `field_date_value` AND `field_date_end_value` OR `time()` is \< to `field_date_value`

(ps: time() = 06-26)

I coded this for that :

And my render is :

So I think this code find some good value in database but is returning only 1 case with the first date which is wrong instead of the good which is the second and the third.

My wish :

Thanks in advance.

# Answer
> 0 votes
As far as I can see you could already help your self by making your conditions more simple:

> just want to make a request to render all node when time() is between field\_date\_value AND field\_date\_end\_value OR time() is \< to field\_date\_value

So actually your final condition (which is equivalent with what you wrote is) time() \< field\_date\_end\_value

Also I advice you to use the request time (from Time service) instead of time: in most of the case is that's what should be used.

---
Tags: 8, database, datetime
---


# Question
Title: How to print the file description to my twig template?
I'm trying to figure how I can obtain or print the file description that is uploaded on my node and display on my twig template

So far I have tried `{{ file.entity.label }}` which only prints the name of the file. I even tried `{{ file.entity.value }}` or `{{ file.entity.title }}`.

Here is a sample of the code I have been working on

```
{% for file in object.entity.field_file %}

    <li>{{ file.entity.label }}  {{ file_url(file.entity.uri.value) }}</li>

{% endfor %}

```

# Answer
> 8 votes
The `node` variable is available in both `page.html.twig` and `node.html.twig`, so you can get your file description with

```
{% for file in node.field_myfile %}
  {{ file.description }}
{% endfor %}

```

Replace `field_myfile` with the machine name of your file field.

---
Tags: 8, theming, entities
---


# Question
Title: Installation profile - Can I create nodes via yml files? What's the best practice for it?
I've created an installation profile for Drupal 8, which creates content types, taxonomies, blocks and stuff I need for new projects via yml files. Now I also want to create some default nodes.

I could use hook\_install() or the module "default content" to create some nodes, but I'd like to know, if there is a better way for it.

Since we can create content types, taxonomies, blocks, etc. with yml files, I was wondering if it is possible to also create nodes with it.

So my questions are:

* **Is there a way to create nodes via yml files?**
* **What would be the best practice for it?**

# Answer
> 1 votes
That's exactly what the Default content module was built for:

> Default content gives your module and install profile a way to ship default content as well as configuration.

I'm not sure it supports YAML, but definitely JSON and others, so it's basically the same thing.

The docs can be found here.

# Answer
> 0 votes
I think this info's correct:

1. YAML Encoder with Content Serialization: uses Drupal/Symfony serialization framework
2. YAML Content: doesn't use serialization framework, doesn't support export
3. Demo Content: doesn't use serialization framework, doesn't support export

Regarding best practice it might be worth pointing out that after doing a core or contrib update, my understanding is you should update all exported entities, both config and content.

---
Tags: 8, installation-profiles
---


# Question
Title: Migrating sha1 user passwords into drupal 7
I have an old zend 1.8 cms site and I wish to import users into a drupal 7 site so that a user can login with their sha1 password without having to changing it. Once verified convert the submitted password to drupal 7 password in the users table. I would guess I would need to import users without their passwords into the users table and create a separate table to store their sha1 passwords in the database. I would be very grateful if someone can point me in the right direction to achieve this.

```
<?php
$str = 'password';//Users password

if (sha1($str) === '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8') {//from imported users table
    echo "Your password is valid";
    //let user into the site
    //insert into user.pass table password $str $S$DUygh2WJWU3caajVD3mgjIHShYgOTbaZnt9uC8lf6fMNo9lX50nr
}
?>

```

# Answer
> 0 votes
You can use the Migrate framework and easily import accounts into Drupal 7 and it will take care of this for you. Don't bother with separate tables and password lookups and all that.

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

https://www.jeffgeerling.com/blogs/jeff-geerling/migrating-drupal-7-users-site

I can't find an actual example of a class that handles users into Drupal 7, but the Migrate docs are very thorough.

Edit - here is an example: https://cgit.drupalcode.org/migrate/tree/migrate\_example/beer.inc#n212

But in your case you will want to define another database connection in settings.php and define that as the source of the migration.

---
Tags: 7, users, database, migrations, importing-exporting
---


# Question
Title: How to display the calculated priced of commerce products?
I have some product pricing rules that adjust the price a customer will pay. How can I display this adjusted/calculated price to the customer? I want to display the calculated price like a field the way the base price is displayed.

* Is there a field display setting (for example at /admin/structure/types/manage/product/display) that will do this?
* Does it have to be done through rules (if so what event and actions should be used)?

# Answer
When a price field is rendered using the "Formatted price" display formatter, it has a setting for you to choose between displaying the original price as loaded or the calculated sell price for the current user. That second one is the default, so as long as you are using product pricing rules properly (as indicated in the comments), this should just work for you.

If for some reason it isn't you'll need to find and review your display settings for the price field on your various product types. Because the price field that appears on a product display comes from the product entity directly, you have to adjust its field display settings there instead of on the relevant node type. You should find them under **Administration \> Store \> Products \> Product types**. Click the **manage display** link beside your product type and see what it says.

If you get stuck, feel free to join us in the #commerce channel in the Drupal Slack!
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Use previously-submitted values as default values in a GET-method form
I have a custom form defined by the class below :

```
class MyForm extends FormBase {

    /**
     * @see \Drupal\Core\Form\FormInterface::getFormId()
     */
    public function getFormId(){
        return 'my_form_id';
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::buildForm()
     */
    public function buildForm( array $form, FormStateInterface $form_state ){
        $form['my_textfield'] = array(
            '#type' => 'textfield',
            '#title' => t('My textfield'),
            '#default_value' => 'I want the current value here !',
            '#description' => t('Description of my textfield.'),
            '#required' => true
        );

        return $form;
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::validateForm()
     */
    public function validateForm( array &$form, FormStateInterface $form_state ){
        // Not implemented yet...
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::submitForm()
     */
    public function submitForm( array &$form, FormStateInterface $form_state ){
        // Not implemented yet...
    }

}

```

The form is then built in my page controller, using `\Drupal::formBuilder()->getForm()`. It overrides the form's `#method` attribute to `GET` because I want the field state to be present in the URL.

I'm looking for a correct Drupal-friendly way to assign the `#default_value` of my fields with the previously submitted state of the form.

**Edit:**

If I use a classic POST-method form and I add `$form_state->setRebuild();` in `::submitForm()`, I can get my values in `::buildForm()` using `$form_state->getValues()`. And the form is automatically rebuilt with the previously submitted values, without having to assign the default values programmatically...

---

**Could-be-related posts**

# Answer
> 0 votes
My final implementation...

**MyForm.php**

```
class MyForm extends FormBase {

    /**
     * @see \Drupal\Core\Form\FormInterface::getFormId()
     */
    public function getFormId(){
        return 'my_form_id';
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::buildForm()
     */
    public function buildForm( array $form, FormStateInterface $form_state ){
        $form['my_textfield'] = array(
            '#type' => 'textfield',
            '#title' => t('My textfield'),
            '#default_value' => 'I want the current value here !',
            '#description' => t('Description of my textfield.'),
            '#required' => true
        );

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

        return $form;
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::submitForm()
     */
    public function submitForm( array &$form, FormStateInterface $form_state ){
        // Nothing to do here...
    }

}

```

**MyController.php**

```
class MyController extends ControllerBase {

    public function index( Request $request ){

        // Here I can use $request->get('my_textfield') if needed

        $form_state = new FormState();
        $form_state->setRebuild(); // So that the form is rebuilt with previously submitted values
        $form_state->setMethod('GET'); // So that the form is submitted via GET method (URL)

        return \Drupal::formBuilder()->buildForm( '\Drupal\my_module\Form\MyForm', $form_state );
    }

}

```

# Answer
> 0 votes
You will have to set query parameters on submit and then you can fetch them and use as default values.

**1\] Redirect on submit**

```
$form_state->setRedirect($route_name, $route_parameters, $options);

```

**2\] Fetch query parameters**

```
$params = \Drupal::request()->query->all();

```

---
Tags: 8, forms
---


title: How is user input sanitized?

text:
# Question
Title: How is user input sanitized?
I had to develop a Drupal 8 based website for a client. This client has a quite strict configuration for its firewall and filters the characters used in POST values. It happens to be a bit too restrictive on the contact form for the taste of the marketing department. The security team would consent to lift some character limitations if I could list them the measures used by Drupal and Webform to filter/sanitize user inputs.

I am pretty confident that Drupal does a good job in that regard. I expect a mixture of `htmlentities()`, `filter_var()`, custom functions calls and other related configurations but I couldn't find any details. All my searches on the subject spawns answers around the fact that Drupal *does* sanitize its input, but nothing concrete.

How does Drupal sanitize the user input?

# Answer
Drupal uses Twig's autoescape feature, which in turn uses `escape`, which itself uses `htmlspecialchars` to prepare markup safe for output.

`SafeMarkup::checkPlain()` preceded the autoescaping (deprecated now), so you may see that used, and `HTML::escape` can be used if you need to do it manually for whatever reason.

As with all versions of Drupal, filtering is done on output only, not input, so `filter_var` and friends aren't involved.
> 5 votes

---
Tags: 8, webforms, security
---


# Question
Title: Acquia cloud installing a module: private key file
I'm currently building a CMS using Drupal 8 hosted in Acquia Cloud. At this time of the process, the goal was to do the setup of URL Patterns.

In order to do this, I need to install the module Pathauto and its requirements (Token and CTools) \[as it's shown here\].

After some going around, found out the installation of modules isn't actually as straightforward as clicking a button, inferred from seeing the following screen (doesn't appear that functionality).  After some research, found that there's a page in Acquia documentation with an explanation of how to install a Drupal module on Acquia Cloud.

The approache I started doing was to develop the application locally using Acquia Dev Desktop, add new modules using local tools like Drush or the Update Manager, and then push the code to Acquia Cloud with Acquia Dev Desktop.

After installing Acquia Dev Desktop, I need to do the login using the Acquia Cloud credentials.

While on it, there's a button meant to allow to clone this site locally, which is what I want to do now.

After filling up all the details (sanitizing the database),

I'm asked to provide a private key:

In order to get that key, Acquia allows to generate automatically a public key (using the button "Generate" in this last image)

Once the public key was generated, to complete the process I'm redirected to this link. Following it I was able to generate the SSH key which appears under

> /app/profile/ssh-keys on my Acquia Cloud account.

After this, *I'm in need of a Private key file to continue the process and i'm blocked*. Given this information bellow, **what can I do to have it**?

Attentively

Tiago

# Answer
> 0 votes
The solution was to **forget about Acquia and start using cPanel.**

In here, was as straightforward as creating a subdomain, taking advantage of Softaculous scripts by installing in that location the 8.4.3 version of Drupal.

Once installation was complete (which was a matter of seconds) and I've logged in as admin, **installing a module was never easier**!

See for yourself:

Tiago

# Answer
> 0 votes
You can use the key you generated from Acquia Dev Desktop by following these additional steps (I was in a similar situation and this resolved for me):

1. Log into https://cloud.acquia.com
2. Open "Account Settings" (click account icon in the upper right corner, then click Account Settings)
3. Click "SSH Keys" on the navigation menu on top.
4. On the SSH Keys screen, you can add new keys by clicking "Add SSH Keys" in the upper right corner.
5. Add the public key that you want on your account (info from key generated by Acquia Dev Desktop).

After adding your public key to your Acquia account, you should be able to use the key from Acquia Dev Desktop.

---
Tags: 8, acquia-dev-desktop, acquia-cloud, ssh
---


# Question
Title: How to make form_alter act upon boolean choice rather select list
I am working on a form\_alter() based on Form API **states** which is about switching a field choice based on the value of a select field as below;

```
'select[name="field_date_type"]' => ['value' => 'allday']

```

I would like to know what syntax is required for changing the field widget from **select** to boolean or checkboxes or radios.

I have tried switching **select** to *boolean*, *checkbox* and *radio* but none are working for me.

What am I doing wrong?

# Answer
> 2 votes
Assuming you mean *checkbox* (HTML doesn't have a *boolean* input type), the property is `checked`, so you can use:

```
':input[name="field_date_type"]' => ['checked' => TRUE]

```

---
Tags: 8, forms
---


title: Add dynamic path to user profile

text:
# Question
Title: Add dynamic path to user profile
I would like to add a dynamic path '/myprofile' as an alias for /user/{uid}/profile . (Always using the current users id.) If possible I don't want to use redirect.

I tried to do the following in my controller with a route /myprofile:

```
public function myProfile() {
  $sub_request = Request::create('/user/' . $this->currentUser->id() . '/profile', 'GET');
  $subResponse = $this->httpKernel->handle($sub_request, HttpKernelInterface::SUB_REQUEST);

  return $subResponse;

```

}

Somehow this seems to work, as the page is displayed correctly but somehow the form is not working anymore. When I update the values and save nothing happens.

I also thought about adding a new route in a route subscriber, but I don't know how. https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones does not help, as the last part about adding routes does not contain any example.

# Answer
> 0 votes
Your sub request doesn't work for a form. When you submit the form the POST request can't reach the form inside of the sub request. So you probably would need to work on building a better request which contains the POST data. But I don't think you need a sub request, you can return the user profile directly from the controller:

```
public function myProfile() {
  $user = User::load($this->currentUser->id());
  return $this->entityFormBuilder()->getForm($user);
}

```

---
Tags: 8
---


# Question
Title: Custom html.tpl.php file is not getting picked up
I have a page with a url alias of say /food/tacos

I have created html--food--tacos.tpl.php to include some javascript only on that page. I've used this method many times (on other sites) with no problems, but Drupal (7) doesn't seem to be picking it up this time.

I have cleared all caches.

Theme debug offers the following suggestions, none of which seem to recognize the path alias. I would prefer to use the alias as I may use this theme in multiple places where the node number would not be the same.

```
<!-- THEME DEBUG -->
<!-- CALL: theme('html') -->
<!-- FILE NAME SUGGESTIONS:
   * html--node--3.tpl.php
   * html--node--%.tpl.php
   * html--node.tpl.php
   x html.tpl.php
-->
<!-- BEGIN OUTPUT from 'sites/all/themes/mytheme/html.tpl.php' -->

```

How can I get this working with the alias?

# Answer
You have to add a theme hook suggestion (example from here):

```
function THEME_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
   // If the content type's machine name is "my_machine_name" the file
   // name will be "page--my-machine-name.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
   }
}

```

Use this in code in your template.php file in the theme directory and, obviously, **change it** :)
> 0 votes

---
Tags: 7, theming
---


# Question
Title: relative path in blocks - multilingual - does not work
I'm using Drupal 7 with i18n modules. I have 6 languages on my site. The relative paths are working fine except for: the relative paths in blocks for the languages other than the default language.

On my front page I have several blocks. If I add the relative path in a block on my English (default language) front page (www.example.com) it works. If I add a relative path in a block to my French front page (www.example.com/fr)

```
<a href="page-in-french">Link in block on the French page</a>

```

Then my expectation was to get to this page

www.example.com/fr/page-in-french

but instead I get to the page:

www.example.com/page-in-french

which obviously does not exist.

I know that I can manually add in the relative path the language code

```
  <a href="fr/page-in-french">Link in block on the French page</a>

```

but since the URL that I'm accessing is www.example.com/fr , then a relative path should not contain the "fr/" since it is already in the URL.

How can I set the relative path to just "page-in-french"?

Thank you

# Answer
> 0 votes
There are 2 components in the multilingual Drupal WRT which language to show: **Content** and **Interface**. `/page-in-french` refers to Content, `/fr/` refers to the Interface language.

Without some additional "guidance" Drupal will link to exactly the link you tell it to. In D7 translations of nodes are new nodes (with different IDs) so it makes sense there is nothing to show for `/page-in-french` since there are no nodes in English with that name.

## Use `multilink` to redirect to content in language matching the interface language

If you want to make the Drupal be aware of language context in such a way to redirect to a relevant content translation to match the interface language use Multi-Language Link and Redirect (MultiLink).

It works by enabling it on the text Input filter you're using.

It comes with a special syntax to include links to nodes `[NID:text]` but you don't have to use it! The redirect will work even for HTML links with classes and IDs. Which means you don't have to edit the links you already have.

If you want to control which text to display in the link you can do this in your English block:

```
<a class='someclass' href='/page-in-english'>Custom English text</a>

```

and this in your Spanish block:

```
<a class='someclass' href='/page-in-english'>Custom Spanish text</a>

```

The `href` attribute stays the same, only the link text changes.

If you want to display node title as the link text (the title of the relevant language translation) you can rely on Multilink syntax:

`[34: $]`

where the 34 is the NID of the English node $ represent relevant node title. This will display node 34 on the English side with node 34 title, and on the Spanish side it will display whichever node is the Spanish translation of node 34, and the link text will be the title of the translated node.

### Check your Languages Detection and selection settings

Make sure you have **URL** set as the first enabled option. This will make sure the redirect respect the Interface language you're using.

If you give advantage to the **User** option, and a user has Spanish set in their profile, they would never be allowed to see English pages, as long as they're logged in they'd always be redirected to Spanish.

# Answer
> 0 votes
Given more information in your latest comment it seems like your problem isn't related to Drupal at all, it's just the way you structure your href attribute.

This might be down to literally omitting the starting `/` in your href attribute. Without the starting `/` the link is assumed to be relative to the current page!

With the starting `/` the link is assumed to be relative to the baseurl.

Since you're planning on showing the link on many different pages, you can't use URL that is relative to the current page, you have to use the URL that is relative to the domain name: `<a href="/fr/page-in-french">`, and not: `<a href="fr/page-in-french">`.

The way you describe it in your latest comment, that links turn out correctly on all pages except from the front page, is only a coincidence. You obviously don't have any deeper links (`/fr/first/second`), you only have one level after the lang (`/fr/first`). On the "one level pages" your link is evaluated to be relative to that page: `/fr/your-link`.

On a page with deeper path structure your link would evaluate to: `/fr/first/your-link`. Which doesn't exist and you don't want that ;)

You must use the starting `/` in your href attributes if you want your link to always be relative to the baseurl, and not to the page you're currently viewing.

When you structure your href to `/fr/page-in-french` the links will always be correct, no matter which page they're displayed on.

But it also means the link will always link to the French interface and the French node. Even on English pages with English interface.

If you expect to use that same block on all languages, and you expect to display related language links (if on a French page show link to French node with `/fr/`, if on an English page show link to English node without the lang code), then you need to use the Multilink module, as I described in my previous answer.

Another option is to create different blocks (or Translate the existing block) so different blocks/translations are shown on different languages. This is a good solution if you don't have a lot of links. You'd have to manually writeup all the links correctly for all the languages (all English links in English block, then separately all French links with `/fr/` in French block), and check them all. So it's doable if you don't have a lot of links and languages.

For all other cases I'd recommend Multilink module as the only sensible solution.

---
Tags: i18n-l10n
---


# Question
Title: Use custom form submit function inside class
In my controller I am loading a form and including one custom submit handler. However the submit function is not called. I think that it's either not found or not accessible as it is inside the controller class:

```
class MyController extends ControllerBase {

  //...

  public function myProfile() {
    $user = User::load($this->currentUser->id());
    $form = $this->entityFormBuilder()->getForm($user);

    $form['actions']['submit']['#submit'][] = '::_custom_submit_form';
  }

  protected function _custom_submit_form(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $form_state->setRedirect('<front>');
  }

}

```

If I use hook\_form\_alter it works, but I don't want to use a hook as I can directly manipulate the form.

# Answer
> 5 votes
To understand why your code is not working, you need to understand how the form API works:

1. The form definition is called
2. Any form alter hooks are executed, altering the form
3. The render array is cached
4. The form is rendered as HTML and sent to the browser
5. The user submits the form
6. Drupal checks that the submitted values match the cached form. If values do not match, the values are rejected by Drupal's security system

When you call this code:

```
$form = $this->entityFormBuilder()->getForm($user);

```

The caching mentioned in step 3 above has already happened. So when you do this after that line of code:

```
$form['actions']['submit']['#submit'][] = '::_custom_submit_form';

```

The submit handler is never called, since the form was cached before this line of code, and therefore your submit handler does not make it into the cache.

To add a submit handler to a form, you need to implement `hook_form_alter()` (or a variation), which will add the handler before the caching happens. Or, you can extend the form class you are working with, add your own ::submitForm() handler, then call the parent submit from that.

---
Tags: 8, forms
---


# Question
Title: Is it possible to filter by taxonomy field?
Is it possible to filter by taxonomy field in a view, using Drupal 7?

I will try to explain the problem with a silly example: let's say I have a list of countries that are a taxonomy term and each country has a field "Language".

I also have a list of items each linked to a specific country.

I would like to be able to filter by language, getting only those items that have a country where e.g Spanish is spoken.

# Answer
> 1 votes
Absolutely. When creating a new View, be sure to show "Taxonomy Terms" rather than Content. Change "of type" to be Countries.

After that, you should be able to add a Filter for the language field.

---
Tags: 7, views
---


# Question
Title: Renaming a webform handler - old class stuck in DB despite clearing cache
I'm creating a custom webform handler plugin based on the advice here, adding the class, in the correct directory, to an existing module.

I got the class name / some of the docblock info wrong initially - and need to change it. Having run `drush cr`, the listing on */admin/structure/webform/config/handlers* seems to be stuck on the old entry.

I get **"Cannot declare class ... because the name is already in use"** errors when trying to add the handler to the form, for a class name that I'm no longer using, and which, having cleared the cache, definitely isn't in `cache_discovery.webform_handler_plugins` in the DB.

I've also swapped browsers.

What am I missing?

# Answer
> 2 votes
Sometimes, especially with a local dev environment, after you have tried every other route the only other avenue is to restart the PHP service and/or reboot the server/VM. This should clear system caches and often times will resolve this issue.

---
Tags: 8, webforms
---


# Question
Title: Is Drupal 8 ready for big website development?
I have a good experience with Drupal 7 and build many website using D7 Verison.

Now, i am in process of building a new big website with plenty of user interactions by collecting data from webforms...

And to avoid the nightmare of ugrading my website from D7 to D8 1 or 2 years later... So i decided to start my new project using the D8 version.

I was checking some of the modules required by my project and found that almost all modules do not have stable releases yet (Yellow Color)

The website will be heavily based on:

* Rules
* Group
* Webform
* Bootstrap Theme
* Quick Tabs
* Display Suite
* Footable
* Field Permissions

---

UPDATE (MORE IN DEEP EXPLANATION)

1) There is no team behind the project, only 2 person are working in this project with very limited coding capability but good knowledge about Drupal, modules and its functionality...

2) The project is personal so no one is hiring us and we hope within around 2 months we will have the first stable release of the website online.

3) The website concept is pretty simple and forward, for example:

_ Webform a user can fill it to answer some question.

_ Automatically creating of nodes upon webform submit using rules.

_ Grouping registered users on the website within Groups (Please note i am using "Group" module and not the "OG" module.

_ Sending a simple email for administrator when a user sumbit a webform.

_ Display created nodes using views.

_ No complicated requirement is needed for such project, at least for the coming 2-3 years from the website launching date.

_ Open Webform in dialog (Popup window)

_ Ajaxify all pages, nodes... (maybe not all but most of them) (I mean by ajaxify is loading content withoit refreshing the page)

WHAT DRUPAL 8 IS OFFERING OUT-OF-BOX:

_ Views.

_ Dialog (open any link with the specific class)

_ Entity reference field

_ Telephone field

_ Ajaxify (Not sure if come out-of-box)

_ Long support (maybe 6-7 years ahead)

_ Quick edit

_ Responsiveness.

_ More faster and more secure.

_ many other features...

NOTE:

_ the project is doable with Drupal 7 but i am affraid from the time and effort required to migrate from D7 to D8 especially when i will have around 100000 registered users and around 500000 nodes (After max 1-2 years from the project launching date)

---

I will be facing plenty issues by using such modules in D8 or they are already safe to be used ?!

In other hand, is it better to stick with D7 for time being until D8 becomes more stable ?

Thank you for your help and ideas,

# Answer
Personally, I think Drupal 8 is now in a pretty stable place, where I would be confident in starting a lot of projects with it, however that is based on my experience with Drupal 7 and 8 and knowing that myself or the company I work for would be doing the work. It's also possible there would be briefs where I would very heavily consider using Drupal 7 still, depending on all the relevant factors.

There are still a number of areas where contrib modules are not yet ready for all use cases (or in some areas any use cases) without the ability in your team to either fix those modules or write your own custom code. That may or may not be okay depending on your team, budget and timeline.

There are too many variables to be able to answer this properly for your specific situation.

It depends on the project requirements (with more specifics than in your question above), the skills of the project team, the skills of the support/maintenance team for after the project goes live, the timeline of the project build, the budget of the project build, etc.

To work this out though, I recommend checking up on the statuses of these modules and see if they are mature enough for your liking. This may involve checking things like:

* What versions are available?
* How many people are using the Drupal 8 versions?
* How many issues are open for D8 versions? Are they bugs or feature requests? If they're feature requests are the missing features ones you need? What kind of support requests are being created and do they make it seem like there are some issues?
* If the module is not ready enough, how active is the maintainer? When were the last commits, etc.

In some cases those things might be enough to satisfy you that you have enough knowledge to decide. In others you may still be unsure, in which case I would quickly stand up a dummy Drupal 8 site for some prototyping, install the modules you want to check and try them out. See if they are as stable as they claim to be and that you can do what you need.

Then you an decide if it's ready enough, or if it's not but you can deal with the missing parts within your team, or if you think it would be better to use Drupal 7 and upgrade to Drupal 8 in future.

Prototyping like that obviously takes some time, so you need to account for that in your project plan. It is however, generally significantly less time consuming than just going full speed ahead into development and then discovering later on that you can't do something you need to do and having to deal with that.
> 2 votes

# Answer
From an overall perspective the answer to this too-broad question is:

Absolutely ready.

Safe to use.

Huge improvement.

I'm saying from my own experience.

Just one thing: Get used to Composer, Symfony and to Drupal's new configuration management. It's a bliss. Every single one of them. It will take time to adapt, yes, but after a while you'll work much more efficiently compared to D7. Symfony, OOP, standardized, everything has its place.

I recommend this official Composer template https://github.com/drupal-composer/drupal-project and https://github.com/drush-ops/drush-launcher to kick-start.

Don't stick to D7. It's still cool, but it's somehow a dead end (sorry). Plus you will have to migrate to D8 or D9 later anyways. With D8 the upgrade path to D9 probably will be seamless. No migration needed.

Move forward.
> 1 votes

---
Tags: 8
---


# Question
Title: Can Drush be assigned as a ssh users default shell?
Problem: I need to allow ssh access to my web server to dev team in order to use Drush. I am reluctant to give them full SSH access due to lack of trust in their SSH skills and knowledge.

Attempted Solution: I tried creating users on my server and only allow them access to Drush using the following command.

`useradd -s /usr/bin/drush drushuser`

On logging in with drushuser, a list of commands displays and logs out immediately.

I do something similar with git and git-shell, I set the /usr/bin/git-shell as their default shell and it does allow them to push and pull content remotely.

Is there any way I can get the same results for drush?

# Answer
Drush has some sort of interactive shell - try `drush php:cli`. (You would created a script `/usr/local/bin/drush-shell` similar to git-shell.) However, I just tested and it doesn't seem to work for Drush 9. If you are still using Drush 8, it seems to work just fine (as `drush core-cli`). Disclaimer: I haven't actually tested this as a login shell.

The other more standard approach is to use lshell and set it up so Drush and needed tools can be used. I haven't tested this either - sorry.
> 0 votes

---
Tags: drush
---


# Question
Title: I cannot upload an image - 404 ajax error
When I try to upload an image, image is not generating and I always get ajax error.

I cannot upload an image.

I get a 404 ajax error.

I use Drupal 8.54

php.ini:

```
memory_limit = 254M
upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 90

```

No error - Recent log messages.

The files directory ( sites/default/files ) permissions - 777

I don't find any solution or references about that.

Edit:

I can't upload file.

When I want to upload more than 8KB files, get ajax error.

# Answer
This part of the AJAX error message can be helpful for you:

> the requested url /@custom was not found on this server

This may have the following root causes (including but not limited to):

* .htaccess settings
* Your settings.php
> 0 votes

---
Tags: 8, ajax
---


# Question
Title: Ajax Forms created by Ajax Drupal 7 ERROR JAVASCRIPT
I read a lot of documentation, specially this post https://www.drupal.org/node/2009252 but doesnt work for me.

This is my code, and the main problem is that **i dont get the javascript** in function *hcat\_my\_account\_create\_companion\_ajax\_callback* from the page callback '*my-account/ajax/create-companion*' then **I cant send my form by ajax.**

```
function hcat_my_account_menu() {
    $items = array();

    $items['my-account/ajax/create-companion'] = array(
        'page callback' => 'hcat_my_account_create_companion_ajax_callback',
        'access callback' => TRUE,
     );

    return $items;
}

function hcat_my_account_create_companion_ajax_callback($form, &$form_state) {

    $submission = (object) array();
    $form = render(drupal_get_form('hcat_my_account_acomp_form', null, $submission, true, false));

    $settings = FALSE;
    $javascript = drupal_add_js(NULL, NULL);
    if(isset($javascript['settings'], $javascript['settings']['data'])) {
        $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, '.drupal_json_encode(call_user_func_array('array_merge_recursive', $javascript['settings']['data'])).'); console.log("He cargado el Drupal.settings");</script>';
    }

    form_load_include($form_state, 'inc', 'node', 'node.pages');
//I CANT PASS ANY JAVASCRIPT. WILL DISAPPEAR.
    return "<div id='new-form-ajax'>".$form.$settings."</div>";
}

function hcat_my_account_acomp_form($form, &$form_state, $vars) {

    $form['hola'] = array(
        '#type' => 'textfield',
        '#default_value' => "Vamos",
        '#attributes' => array('class' => array('my-account-input-edit')),
    );
    $form['submit_save'] = array(
          '#type' => 'submit',
          '#value' => 'Vamos que te quda poco',
          '#ajax' => array(
                'callback' => "hcat_my_account_create_attend_form_submit_ajax",
                'wrapper' => "hcat-my-account-acomp-form",
                'method' => 'replace',
                'effect' => 'fade',
              ),
    );

    form_load_include($form_state, 'inc', 'node', 'node.pages');

    return $form;
}

function hcat_my_account_create_attend_form_submit_ajax($form, &$form_state) {
    return "Desde la funcion hcat_my_account_create_attend_form_submit_ajax";
}

```

# Answer
> 0 votes
I found this way to resolve it. Creating another form whose submit return the form that i want. The code is:

```
function my_module_botton_create_form($form, &$form_state) {
    $form['create_form'] = array(
        '#type' => 'submit',
        '#value' => '',
        '#ajax' => array(
            'callback' => "my_module_to_create_form",
            'wrapper' => "new_acomp_form",
            'method' => 'replace',
            'effect' => 'fade',
          ),
    );

    return $form;
}

function my_module_to_create_form($form, &$form_state) {

    $form=drupal_get_form("my_module_acomp_form");

        $output = array(
            '#type' => 'ajax',
            '#commands' => array(
                array('command' => 'ajax_create_form_acomp', 'data' => drupal_render($form)),
            ),
        );

        return $output;
}

function my_module_acomp_form($form, &$form_state) {

    ...

    return $form;
}

```

The JS is

```
Drupal.ajax.prototype.commands.ajax_create_form_acomp = function (ajax, response, status) {
    $('#new_acomp_form').replaceWith(response.data+"<div id='new_acomp_form'></div>");
    //Drupal.behaviors.hcat_my_account.check_if_attendant_exits();
};

```

---
Tags: forms, ajax
---


title: D8 alter hook sequence

text:
# Question
Title: D8 alter hook sequence
I was wondering if using `hook_module_implements_alter()` is a good practice in D8 also to alter the order of execution of hooks?

I came to hear that it is suggested to do this with `events` that was introduced in D8 which will be a better way, but I could not find any reference that says not to use `hook_module_implements_alter()` in D8. One such ref.

If using `events` is advised, can someone put up a small example as to how to do that?

Thanks

# Answer
> 1 votes
> I was wondering if using hook\_module\_implements\_alter() is a good practice in D8 also to alter the order of execution of hooks?

Yes it is - in fact it's the *only* way to alter the order of hook execution.

Events are something different. Their execution order is set in the implementation of each handler, and can't be affected by any hook.

---
Tags: 8, hooks
---


# Question
Title: Change field from Multi-Value to Single-Value
I have a developing a website with a reference term field with multi value. But after the client change the "rules" I need to change the field from multi value to a single value field, but the field as Data, lot's of data.

Is it possible to change from multi value to single value? (the field only as one value inserted and the real object is to use those values).

# Answer
> 1 votes
## Use VBO

Introduce a new, single-value field in the bundle, then use Views Bulk Operations (VBO) to copy the data from the old multi-value field to the new single-value.

VBO have an option to "Execute Arbitrary PHP Script" where you can insert a PHP-snippet to do the copying, something like:

```
$object->field_foo['und'][0]['value'] = $object->field_bar['und'][0][1]['value'];

```

The PHP above is only an example. Use `dsm($object);` (requires Devel installed) to figure out the datastructure of the entity object you need to manipulate.

When done, delete the multi-value field.

## Alternate solution: Node convert

It is also possible to do bulk conversion with Node convert.

To use this method, you first clone the content type, then change the multi-value field into a single-value field in the clone. Node Convert let you map content field by field, so you copy most fields directly, and then copy the first value of the multi-value field into its corresponding field.

The disadvantage with this method is that the machine name of the type changes, so you may need to fix that in a number of places if it is used a lot. The advantage that you can do it all in the GUI, no need to write PHP.

# Answer
> 0 votes
To do this without changing the database, you could use a custom module to leave the database field as-is multivalue, but change the UI so it only allows users to see/choose a single value by altering the edit form to use a single-value dropdown:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Change multivalue field in database to single-value field on node create/edit pages.
  if (in_array($form_id, ['node-article-form', 'node-org-article-form'])) {
    $form['field_multi_thing']['widget']['#multiple'] = false;
  }
}

```

This is particularly useful if you have a base field that is shared across content types that needs to be multi-value on some content types, but single-value on others.

---
Tags: entities
---


title: Commerce without billing address

text:
# Question
Title: Commerce without billing address
We our developing a Drupal 8 Commerce website that does not need anything to do with addresses

* The products are all virtual: membership and event tickets.
* The billing is using PayPal express which takes care of billing address.

Therefore we don't want to prompt the customer to fill in an address, or store an address, or give them an "addresses" tab on their profile. Please can anyone advise how to configure this scenario?

So far we have considered:

1. Edit the commerce flow. The BillingInformation pane gets included via PaymentInformation. If we remove PaymentInformation it does suppress the prompt for address and suppress the creation of a profile, but unfortunately it seems to stop the payment step from working properly.
2. Edit the customer profile form display to disable the address field. This does suppress the prompt for an address, but we find that an empty profile is created for every order.
3. Delete the customer profile type. We didn't try it yet because it seems likely to break the site as the Commerce core code has various hard-coded references to that profile type.

As an secondary question, we'd also prefer not to enter an address for the store as it does not have a physical address. However the address seems to be mandatory and does not allow country=none. We have entered a dummy value which seems to work as so far we haven't seen it used. Can we trust the dummy address will never be used, and if so, would it be reasonable to say that the address ought to be an optional field?

# Answer
> 2 votes
Credit: many thanks to @Bojan for the information in his answer, please join me in +1 to him. I created this new answer to explain some details more clearly and add some new factors that I have discovered.

1) To avoid the empty profile:

* EITHER apply the "highly experimental" patch from this issue
* OR derive your own class that extends PaymentInformation and cut out everything relating to profiles. However in that case you will hit this issue.

2) If there is just one payment method, this leads to an unwanted empty "Payment information" pane. One way to fix that is to alter the checkout pane and set wrapper\_element = "container".

3) If there is just one payment method, then when logged in, the whole "Order information" step is not necessary. One way to fix that is to edit the checkout flow and move "Payment information" to the review step. However you will then hit this bug and need to apply the patch.

# Answer
> 4 votes
The store address is used for calculating taxes. It doesn't have to be a physical store address, enter the address the business entity is registered to.

On the store edit form select a single "Allowed billing country". That will hide the country selector on all of your address fields.

Then go to `admin/config/people/profiles/manage/customer/fields/profile.customer.address` and under "Field overrides" select "Hidden" for each field. That will hide the other address subfields.

You need to be on the latest Commerce release for this to work.

(And yes, an empty profile with just the country code will be created for each order. There is no way around that currently)

---
Tags: 8, commerce
---


# Question
Title: How can Drupal be made to serve with root-relative paths?
I'm trying to avoid serving pages that load css and js resources through URLs that specify either http or https. (I'm trying to find a workaround for the problem described in this question, in case a real solution cannot be found.)

Because Drupal is specifying http:// for the href for all the CSS and JS files, when the server erroneously switches to https, as described in the aforementioned question, the browser seems to be ignoring all these files, and I get an unstyled page.

Instead of

```
<link type="text/css" rel="stylesheet" href="http://www.example.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

```

(etc.)

I'd like to serve

```
<link type="text/css" rel="stylesheet" href="/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

```

or even

```
<link type="text/css" rel="stylesheet" href="//www.example.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

```

Can I make Drupal serve URLs that don't specify protocol?

# Answer
> 10 votes
You can use a template process (YOUR\_THEME\_process\_html) hook to rewrite all resource urls (js and css) using a regular expression.

Here is an example which transforms all `http://` or `https://` to `//`:

```
function YOUR_THEME_process_html(&$vars)
{
    foreach (array('head', 'styles', 'scripts') as $replace) {
        if (!isset($vars[$replace])) {
            continue;
        }

        $vars[$replace] = preg_replace('/(src|href|@import )(url\(|=)(")http(s?):/', '$1$2$3', $vars[$replace]);
    }
}

```

# Answer
> 2 votes
This has been fixed in Drupal 8. In Drupal 7, there is an issue about fixing it.

# Answer
> -1 votes
We had that same issue with a website we were developing and could not come to a resolution on why some of the paths would be https while others would be http. The work around, which you may not like the answer, was to use the Pathologic module which turns everything from an absolute to relative so your forms would use a /path-to-form instead of http://www.whatever.com/path-to-form.

---
Tags: 7
---


# Question
Title: Is there a way to execte jquery event after ajax callback has been completed?
Having a simple form with few input fields. After clicking on ajax callback submit button, I'm returning the table element.

## Code:

```
//Hypertension treatment
        $form['hyper_treat'] = array (
      '#type' => 'radios',
      '#title' => ('Hypertension treatment:'),
      '#options' => array(
        'y' => 'Yes',
        'n' => 'No'
      ),
    );

//Hypercholesterolemia
    $form['hyperchol'] = array (
  '#type' => 'radios',
  '#title' => ('Hypercholesterolemia:'),
  '#options' => array(
    'y' => 'Yes',
    'n' => 'No'
  ),
);

//submit button
    $form['action'] = [
    '#prefix' => '<div id = "ajax_submit">',
     '#name' => 'ajax_action',
    '#type' => 'button',
    '#value' => $this->t('Submit'),
    '#ajax' => [
    'callback' => '::setMessage',
    'wrapper' => 'scrollable',
    'method' => 'replaceWith',
    'effect' => 'fade',
    ],
    ];

    //table
    $form['table'] = array(
    '#prefix' => '<div id="scrollable" class = "col-md-8"><h4>View Data</h4>',
        '#type' => 'tableselect',
         '#suffix' => '</div>',
        '#header' => $header,
         '#options' => $options,
        '#disabled' => $disabled,
        '#attributes' => array('id' => 'sort-table'),
        '#empty' => t('Select criteria and search data'),
      );

//callback function
   public function setMessage(array $form, FormStateInterface $form_state) {
  $options = getOptions(); //gets the associative array
  $form['table']['#options'] = $options;
  return $form['table'];
}

```

I had issues with the pagination and sorting of the table returned using ajax. So I thought of using "Datatables" as the alternative option.

So after the callback, I would want to apply the below jquery to have the table shown as a datatable.

```
 $('#sort-table').DataTable( {
        order: [[ 1, 'asc' ]]
    } );

```

Tried executing the 'mousedown' event for the button but the jquery executes before the ajax callback.

Is there a possible way to represent the $form\['table'\] element returned from the ajax callback, as a datatable?

Triggering any other event after table returned would display it as a datatable, but I'm looking to have the returned table displayed as a datatable immediately after the $form\['table'\] is returned. This happens only when the jquery snippet is executed immediately after the table element is returned from the ajax callback function.

# Answer
You can use custom ajax commands for this. Ajax commands are php classes that correspond to a JS function on the server, which the Drupal JS API calls after Ajax responses.

At a quick lookover, this tutorial looks like it gives a good overview on how to create a custom Ajax command in Drupal 8.
> 1 votes

# Answer
jQuery has `.ajaxComplete()` and `ajaxSuccess()` methods among other ajax event handlers. So on the client side you could try something like this:

```
jQuery.ajaxSuccess(function(){
    $('#sort-table').DataTable( {
        order: [[ 1, 'asc' ]]
    });
});

```
> 1 votes

---
Tags: 8, javascript, ajax
---


# Question
Title: How can I generate a usable dynamic PDF from a Drupal view?
My goal is to generate a PDF view of a content node. I've set up the Views PDF module with the TCPDF class, but performance is awful. Not just slow. I mean AWFUL. It's an aggravating experience when viewing a simple page of content as a PDF, and downright painful when viewing content that should be several hundred PDF pages long. Totally unacceptable.

Does anyone have a good solution for combatting this? All I'm looking to do is take a single node and offer a "view as PDF" link/functionality. It seems like this should be pretty straightforward, but I haven't been able to solve that yet.

Any help would be appreciated. Thanks!

# Answer
> 1 votes
I had never had any success with the html\>pdf generating tools for PHP coming out looking 1:1 without issues ranging from style to markup to server side error with the libraries and/or incompatibility with PHP versions, package errors and whatnot.

Another option is to use PhantomJS or an equivalent tool to use a headless browser to output a PDF file for you. Note though, that PhantomJS is possibly going to no longer be maintained, as Chrome now has a headless equivalent.

However, there is a module for Drupal 7 and 8 that provides this functionality (disclosure, I am a maintainer) but it may take a little elbow grease on your end to get it to work the way you'd like. A base js controller for PhantomJS is provided, but you can alter it. If all you need is an equivalent of doing File \> Print to PDF in the browser, this will do it without as much hassle as all the PHP libs.

https://www.drupal.org/project/phantomjs\_capture

As an alternative to that, there is a hosted service provider with an API you can use as well (disclosure - I have nothing to do with it) that might suit you.

# Answer
> 1 votes
From my experience, the kind of functionality "View as PDF" is better answered with a link "Print" or "Save" outputting the content with specific html styled for that purpose. Once I did what you are trying to do, but nowadays I changed my view.

# Answer
> 0 votes
If you want to generate a pdf file from a single node, I would recommend the PDF using mPDF module.

Hope it will help you.

# Answer
> 0 votes
You can implement `dompdf` library in your custom module. It is compliant HTML layout and rendering engine written in PHP. PDF rendering is provided either by PDFLib or by a bundled version the R&OS CPDF class.

The conversion is pretty straight forward. Here is the code example:

```
<?php
// Require the Composer autoloader or use Composer Manager module.
// @see: http://getcomposer.org/doc/00-intro.md
require 'vendor/autoload.php';

// Disable DOMPDF's internal autoloader if you are using Composer Manager module.
define('DOMPDF_ENABLE_AUTOLOAD', false);

// include DOMPDF's default configuration
require_once 'vendor/dompdf/dompdf/dompdf_config.inc.php';

$htmlString = ''; // Replace $htmlString with html of of your content node.
$dompdf = new DOMPDF();
$dompdf->load_html($htmlString);
$dompdf->render();
$dompdf->stream("sample.pdf");

```

---
Tags: files, importing-exporting, views
---


title: Alternative for .inc files

text:
# Question
Title: Alternative for .inc files
I was wondering what is the correct alternative of .inc files in Drupal 8? That is to say, if I want to create some functions that should be only be loaded when required, like it was with `module_load_include()` in D7. Though this function is still there in D8, I hear that this is not the best procedure. Is that so?

I have read somewhere, that using PHP `traits` is considered a better practice here. However, not sure if `use`ing a `trait` inside a .module file is a good approach.

Any help?

# Answer
Actually there seems to be nothing wrong about using `*.inc` files in D8. Have a look at the Update core module. Quite some `*.inc` files present: cgit.drupalcode.org.

---

Nevertheless I tend to follow Symfony's best practice examples when it comes to stuff like that.

\[Symfony Docs\] Organizing Your Business Logic

\[Stack Overflow\] Where to put model helper functions in Symfony2

Means you'll add a new class under `src/Utils`. For example:

```
src/Utils/HelperFunctions.php
src/Utils/FooBar.php

```

And then wherever you need it, you reference it:

```
use Drupal\MYMODULE\Utils\HelperFunction;
use Drupal\MYMODULE\Utils\FooBar;

```

And then you'd call a certain function like so:

```
$site_color = HelperFunctions::getSiteColor();
$foo_bar    = FooBar::returnFooBar();

```

---

And when I'm still unsure, I'll search inside the core and contrib modules how they did it.
> 6 votes

# Answer
In reference to the other answer, the main reasons those .inc files still exist in core is that was just not possible to rewrite everything into classes/services, which is definitely the right way to do it in Drupal 8.

Part by part, more and more functions are being converted to services in Drupal 8 and deprecated in favor of them. Instead of static methods, that's what you should do.

There are plenty of tutorials and documentation on how to create those services and use them, see https://www.drupal.org/docs/8/api/services-and-dependency-injection/services-and-dependency-injection-in-drupal-8 for example.

`trait` can be used when sharing common code between multiple classes that doesn't need to be exposed as it's own service. It's basically just a built-in copy & paste and similar to base classes but more flexible.
> 3 votes

---
Tags: 8
---


title: How can I uncollapse a footer menu?

text:
# Question
Title: How can I uncollapse a footer menu?
I'm theming with Boostrap right now in Drupal 8 and created a footer menu with a bunch of links. The menu is displaying collapsed right now, but I want it to be uncollapsed and display like a default navbar.

While bootstrap displays as collapsed

# Answer
> -1 votes
Edit all of your footer's child menu links and check-mark on each of them *show as expanded*.

---
Tags: navigation, bootstrap-theme
---


# Question
Title: How to limit drush tar-options="--exclude pattern matching to be specific and not recursive
With the folder structure like so
`/site_root
/site_root/images
/site_root/core
/site_root/core/modules/images
/site_root/libraries`
etc

When doing a drush archive dump backup, from the inside `site_root` (usually it's `public_html` but in this case it's another folder), I use
`$ drush ard tar-options="--exclude=images" --destination=~/.backups/[date].tar.gz`

That way the archive dump skips the /site\_root/images folder and the ard is much smaller. Unfortunately for me pattern matching then causes all `images` folders throughout to be excluded due to recursivity. So I would lose
`/site_root/images`
`/site_root/core/modules/images`
etc

I know in linux you can make `tar-options` look at the folder structure by making the pattern relative, like so
`$ drush ard tar-options="--exclude=./images"`
But that is not working for me via `drush ard tar-options`.

I also tried the home folder shortcut `'~'` (which works a treat on `drush ard destination`) like so
`$ drush ard tar-options="--exclude=~/site_root/images" --destination=~/.backups/[date].tar.gz`
But, for some reason, that does not work like it does on the `–-destination` switch.

What is the best way to limit the `drush tar-options="exclude` switch to either no-recursive or pattern match looking at relative path to working directory?

# Answer
> 0 votes
I've found that you can use the current working directory, as the starting point, to force relative urls. It was a matter of getting the syntax correct.

For example if you have your site root in `public_html`, and you are in that location `cd ~/public_html`, you can use drush:

`[user public_html]$ drush ard tar-options="--exclude=public_html/images" --destination=~/.backups/[date].tar.gz`

The key is to navigate to that starting point root folder first.

For example, if your site root was in a subdirectory `subdirectory/siteone`,
go to that location first `cd ~/subdirectory/siteone`
and then use drush:

`[user siteone]$ drush ard tar-options="--exclude= siteone/images" --destination=~/.backups/[date].tar.gz`

---
Tags: drush, backups
---


# Question
Title: Error embedding drupal views to twig template
I'm getting an error `Twig_Error_Syntax: Unknown "drupal_view" function` when I try embedding my views to my twig template `{{ drupal_view('newsdesk', 'block_1') }}`.

I have already installed `twig_tweak`, `twig_extensions` and also installed `twig_extensions` via composer.

I'm not sure what else I'm missing, I've already also cleared the cache during installation

# Answer
That's an error you would get if the twig\_tweak module is not enabled, are you sure you have enabled it? If you have multiple clones of your site, make sure you're on the right one.
> 3 votes

---
Tags: theming
---


title: Check if node update is published

text:
# Question
Title: Check if node update is published
I've a content type with a workflow. I have to notify users when the published version of the node is update.

Have I to check which transition is used? How?

I'm using an hook\_node\_presave.

\[EDIT\] It seems that check if it's the default revision could be right:

```
 $entity->isDefaultRevision();

```

From draft to draft is false. From draft to published is true. From published to published is true.

Could be the right way?

# Answer
> 0 votes
As an alternative, consider using the Content moderation notifications module:

> Allows notifications to be sent to all users of a particular role, or to the content's author when a piece of content is transitioned from one state to another via core's content\_moderation module.

I've used it with good results in several sites.

# Answer
> 0 votes
You can simply get the Moderation state of node in the hook\_node\_presave(). like below:

```
$node->get('moderation_state')->getString()

```

It will give you the string like publish or unpublish.

---
Tags: workflows
---


# Question
Title: Using Drush on a site installed via Composer
I had a Drupal 8 project installed from Drupal 8 sources what had been downloaded from Drupal 8 site. Recently I heard a good thought that it would be more comfortable to have the project originally installed via Composer. I did the migration and now the project has a structure likewise installed via Composer. That is, it has the "web" subdirectory with Drupal 8 files, the "vendor" directory isn't included in Drupal files and so on.

The site worked successfully after migration.

However, I ran into a problem. Namely, after migration, I couldn't use Drush on the project. The following error appeared upon trying to execute `drush cr`.

> Command cache-rebuild needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
> Command cache-rebuild requires Drupal core version 8+ to run.

My colleagues advised me to install Drush-launcher from GitHub as a shell for original Drush. I did it, this problem seemingly disappeared. But I ran into a next one. Namely, Now I can't use Drush for projects made on Drupal 7.

Is it possible to set up Drush for sites installed via Composer and without using the launcher?

# Answer
Acquia Dev Desktop comes with Drush included, and I assume that you could just continue to use that for Drupal 7. However, since you installed Drush Launcher and are using it as `drush` (`drush.bat`), you are shadowing it. Break the shadowing by renaming one of the two.
> 1 votes

---
Tags: 8, drush, composer
---


# Question
Title: Using Workbench Moderation state changes as events
I would like to use the Rules module to send out emails to specific roles whenever a moderation state change event occurs on a node. So if a node is saved, and it goes from *Draft* to *Needs Review*, this rule would be triggered to send out emails to the *Content Approver* role.

This was possible in the Drupal 7 version of Workbench Moderation and Rules, but not out-of-the-box with the Drupal 8 version of these modules.

Any ideas what to do here to accomplish this?

# Answer
We are using Workbench Email to accomplish this on our D8 site, would this work for you?
> 1 votes

# Answer
Since Workbench Moderation is in Drupal Core you can use https://www.drupal.org/project/content\_moderation\_notifications
> 1 votes

---
Tags: 8, rules, workbench
---


# Question
Title: How to add Permalink for custom content type(nodes)
I need to add Permalink for my section/div where the ID will keep on changing whenever i update the page(custom content type).

I have achieved it through client side(Jquery) by find & get ID seems like tedious?

I have checked for module support like permalink & permalink block, Deeplink nothing seems to be helpful?

Is there is any better way to achieve it?

# Answer
> 0 votes
You can create permalinks, better known in the Drupal world as "aliases", using the Pathauto module.

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

See Video Tutorial.

# Answer
> 0 votes
A custom theme preprocess function should help to process the page content and apply what you need (perhaps a numerical ID to each heading?).

Each node normally has a default permalink (regardless of url alias) of /node/\[nid\] which will automatically redirect to the actual path alias. You can see an example of this in most themes with the `<link rel="shortlink" href="/node/[nid]" />` head element.

You could then permalink to individual pieces of content with `/node/[nid]#[heading id]`

---
Tags: 7, nodes
---


title: Custom Block to show taxonomy terms

text:
# Question
Title: Custom Block to show taxonomy terms
I am trying to create a block (that I can reuse in different templates and pages)that shows taxonomy terms (for a specific vocabulary).

I have already created a view to get the term list, and started overriding twig files to modify the display of the view. I modified the following files so far:

* block--views-block.html.twig
* views-view-fields.html.twig

The idea is to implement a bootstrap layout where the "row" div is on the first file and the "col" divs are in the second one.

Overriding those files is working but the layout breaks because there is a lot of unwanted code rendering. For example, the code generated by:

* core/modules/system/templates/container.html.twig
* core/modules/views/templates/views-view.html.twig

Which as I understand I can't override and I shouldn't modify (because they are in /core).

How can I get rid of all the unwanted code those files generate?

# Answer
Sounds like you should enable template file suggestions in your site, this will help you to identify the right target name for a template to override the core files. You can read more about this feature in the docs at https://www.drupal.org/docs/8/theming/twig/locating-template-files-with-debugging
> 0 votes

---
Tags: theming
---


# Question
Title: Sort Node Queries by an entity reference field within a field collection item
I am trying to fetch a list of nodes of a particular content type, alongside their field-collection items. The code below works perfectly for my use case.

```
    function report_cards_get_term_data($type, $term, $session, $student_id, $class){
    $resarr = array();
    $query = db_select('node', 'n');
    $query->join('field_data_field_term', 'ft', 'n.nid = ft.entity_id');
    $query->join('field_data_field_session', 'dfs', 'n.nid = dfs.entity_id');
    $query->join('field_data_field_admission_number', 'rn', 'n.nid = rn.entity_id');
    $query->join('field_data_field_result', 'fr', 'n.nid = fr.entity_id');
    $query->join('field_data_field_class', 'cg', 'n.nid = cg.entity_id');
    $query->join('field_data_field_subject', 'cfs', 'cfs.entity_id = fr.field_result_value');
    $query->join('field_data_field_exam_score', 'ces', 'ces.entity_id = fr.field_result_value');
    $query->join('field_data_field_first_ca', 'cfc', 'cfc.entity_id = fr.field_result_value');
    $query->join('field_data_field_second_ca', 'csc', 'csc.entity_id = fr.field_result_value');
    $query->fields('cfs');
    $query->condition('n.type', $type);
    $query->condition('field_term_value', array('1st Term', '2nd Term', '3rd Term'), 'IN');
    $query->condition('field_session_target_id', $session);
    $query->condition('field_class_target_id', $class);
    $query->condition('field_admission_number_target_id', $student_id);
    $query->addExpression('cfc.field_first_ca_value + csc.field_second_ca_value + ces.field_exam_score_value', 'total');
    //$query->orderBy('cfs.field_subject_target_id->weight', 'ASC');
    $report_card = $query->execute();
}

```

However, i need to sort the result alphabetically by the entity reference name (taxonomy term) called "Subject". The entity reference is a field within the field collections. I know i can use "$query-\>orderBy()" but i can't get it to work. That's why it was commented out in the given code above. Thank you for your suggestions.

# Answer
Solved it myself. I added one more join,

`$query->join('taxonomy_term_data', 'fee', 'cfs.field_subject_target_id = fee.tid');`

Then order by

```
$query->orderBy('fee.name', 'ASC');

```

Then the result was ordered alphabetically by the taxonomy name.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Prevent redirection after comment submission
When a user add a comment on a node, I would like to prevent the page reload.

I added a form\_alter in my theme

```
function theme_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id) {
      case 'my_form_id':
        $form_state['redirect'] = false;
      break;
  }
}

```

But this is not working.

I also tried to replace $form\_state\['redirect'\] = false by $form\_state\['redirect'\] = false but it seems to be the Drupal 7 way to do this.

how could I achieve that on Drupal 8 ?

EDIT

I tried to use a submission handler

```
function theme_form_alter(&$form, &$form_state, $form_id) {
        switch($form_id) {
          case 'my_form_id':
            $form['#submit'][] = 'theme_form_submit';
          break;
      }
    }

function theme_form_submit(array $form, FormStateInterface $form_state){
    $form_state->disableRedirect();
}

```

But it's still not working.

# Answer
> 3 votes
Use `FormStateInterface::disableRedirect()`, e.g.

```
$form_state->disableRedirect();

```

Make sure you run that code in a submit handler for the form, not in the form alter hook.

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


# Question
Title: How to handle a node translation containing an entity reference with a managed field property
I have a custom field that contains a managed file. The node that the field is attached to and the field are enabled for translation.

I create a piece of content, which defaults to the site default language EN. The content contains a managed file, let's say FID 1.

From the admin content screen I select Translate and add a translation. When the node edit form is rendered, it contains the values from the original content as it should, and contains the file information as well, so that I need to remove the original and add a new one.

When I save this version, language ES, both appear on the admin page and in the db. The property for the managed file in ES has FID 2.

The issue is when switching back to English using the language widget on the home page, a 500 is received. The reason is that removing the managed file from the Spanish translation in order to add the correct one resulted in the actual file being removed as well as the FID 1 file\_managed table entry, but 1 still remaining in the property value for the managed file in the custom field.

I could probably finagle the custom field widget to not present a default value for the managed file property somehow in the case of adding the node, but that seems wrong, because it's possible that the user to leave the file the same.

Is there a standard way to handle this?

# Answer
There are a number of issues with reference counting files: see this overview. You might be affected by *$entity-\>isDefaultTranslation() behaves incorrectly when changing default translation, causing file/image field usage to be set to zero, causing files to be deleted*.

Note that due to the potential for lost data, as of 8.4 the default behaviour has been changed to *not* delete files even if their ref count reaches zero. See the CR for more.
> 1 votes

---
Tags: entities, i18n-l10n
---


# Question
Title: Drupal 7 to 8 migration The "taxonomy_term_reference_plain" plugin does not exist
When running the d7\_field\_formatter\_settings.yml (in core/modules/field/migrations/) migration I get the following error.

```
The "taxonomy_term_reference_plain" plugin does not exist

```

Has the taxonomy\_term\_reference\_plain formatter been removed from Drupal 8? If so what is the equivalent in drupal 8 and how can I map taxonomy\_term\_reference\_plain into its drupal 8 equivalent during migration

# Answer
> 0 votes
Yes, taxonomy terms are now treated as general entities rather than special (for the most part), so some of the taxonomy-specific formatters were inevitably removed.

I believe the `entity_reference_label` formatter is the natural replacement for Drupal 8.

---
Tags: 8, migrations
---


# Question
Title: Can a large amount of CSS using <style> tags in a template file slow page load time?
Front page of a site has a HUGE amount of CSS in the front.tpl.php file using tags. Does this significantly reduce page load time? If so, why?

Thank you Drupalists! Or Drupaleers. Drupaleeros. Drupal-Heros!

# Answer
Significantly? depends on how much is your definition huge.

It's best practice to have your style's in CSS file because the browser can cache it. Therefore, on subsequent page loads it doesn't have to download your CSS file again.

The browser doesn't cache your HTML, so it would have to download your huge HTML each and every time.

Caching off

Caching On
> 1 votes

# Answer
This isn't really a Drupal question, nor is it one with a straight forward answer as it depends on your circumstances.

In short the answer is **no**, it won't slow the page down.

CSS is normally included via a linked CSS file because you're usually using the same styles on multiple pages. As @no-sssweat says, these files are then cached by your browser so you don't need to download that data again and again as you navigate.

But! If you have styles that are only used on that page, so won't be needed elsewhere, then by including them in the page you save on the amount of HTTP connections your browser needs to make, and so the page should be faster.

This all depends on your browser, the amount of assets being fetched, etc.

The long and the short of it is that including inline CSS won't slow the **page** down, it might make it faster, but **site wide** \- including shared/reused CSS in an shared CSS file will improve maintainability and allow for improved caching/speed.

As far as Drupal goes, if you are including your CSS files correctly via the theme `.info`, then Drupal will aggregate multiple CSS files into one, so unless you are concerned about the size (for example, you have other landing pages and a lot of people won't need those front page styles), there shouldn't be much difference in the end.
> 1 votes

---
Tags: theming
---


# Question
Title: How do I change the created date when I create a node?
When i do POST request for create node i get error:

```
{
  "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1",
  "title": "Property created cannot be set.",
  "status": 400,
  "detail": "Bad Request",
  "instance": ""
}

```

My restful resource provide this field:

```
protected function publicFields() {
  $public_fields = parent::publicFields();

  // Another fields ...

  $public_fields['created'] = [
    'property' => 'created',
  ];
}

```

I use restful module.

# Answer
> 1 votes
I solved this problem via hook\_node\_presave();

```
function hook_node_presave($node) {
  $node->created = "you_timestamp";
}

```

# Answer
> 0 votes
If you are open to other options, the Rules module could help you with this.

Start by downloading and installing the Rules module (and also enabling the Rules UI module that comes with it as well).

Following that, you can create a New Rule by going to Admin \> Config \> Workflow \> Rules.

Click on the "Add new rules" button.

You can call the Rule whatever you'd like. What matters most is setting "React on event" to be "After saving new content" and then "Restrict by type" to the Content Type of your choice if this limited to one Content Type only.

When you go to the newly created rule, click on the "Add Action" link and then select "Set a data value"

In the Data field, type "node:created" and then click Continue.

Finally, you can specify what you want the new Created Date to be.

---
Tags: 7
---


title: Bootstrap load theme locally

text:
# Question
Title: Bootstrap load theme locally
How do I load the Bootstrap theme (css, js, fonts) locally?

I've searched around the drupal stack exchange, but every suggestion I've come across doesn't solve the problem. It seems like the other option is to create a sub-theme, but I'm not even sure if that will load all the necessary files for bootstrap locally/offline. The whole purpose of this is to load the bootstrap theme and its css/js/fonts without using any internet.

The issue is that I'm seeing the error as another user did like this: https://www.drupal.org/files/issues/screenshot\_218.jpg

There are answers like these below, but there has to be a way to do it without more installation other than drupal modules: https://www.drupal.org/node/1978010 Using own Bootstrap 3 files

# Answer
> 1 votes
You can download bootstrap package and include it in your theme folder.

and go to `admin/appearance/settings/bootstrap` then go to 'Advanced' and change CDN provider to `custom`. give your local bootstrap css,js urls.

if you need to import it to a custom theme you can add it the bootstrap package like below.

your\_theme.info

```
stylesheets[all][] = css/bootstrap.css
scripts[] = js/bootstrap.min.js

```

define the regions you need in your custom theme info file.

remmber to use the 'https://www.drupal.org/project/jquery\_update' module for JS.

# Answer
> 1 votes
It's very simple . Please follow these step to create a sub theme using bootstrap.

1. Install drupal bootstrap theme.
2. copy less folder from starterkits.
3. Download bootstrap css and js file in your sub theme folder.
4. configure you theme info file.

```
 stylesheets[all][] = css/bootstrap.css
 scripts[] = js/bootstrap.min.js

```
5. Enable your sub theme.

If you have any problem I create a video tutorial for you please click on this link tutorial

Thank you

# Answer
> 1 votes
Just for future - if you have no option to compile less files (as me) you can:

> 0) Install bootstrap base theme
>
> 1) Copy less folder from starterkits to `/themes` folder and rename it as you want
>
> 2) Download bootstrap css and js file in your sub theme folder into `/bootstrap`
>
> 3) NEW: copy css file from base theme (from folder `/css/YOUR_BT_VERSION` ) - this is the compiled css - it is nesesary for many drupal features. I add this file in /css folder and rename it to `overrides.css`
>
> 4) Configure you theme info file as usual (change name as folder name), add description...
>
> 5) Add `stylesheets[all][] = bootstrap/bootstrap.css` line and one more line for file from step 4 in your theme.info file - `stylesheets[all][] = css/overrides.css`

---
Tags: 7, bootstrap-theme
---


# Question
Title: How can I sort entity type query results with pseudo values?
Is it possible to use the D8 EntityQuery condition and sort functionality to filter/sort based on the outcome of multiple fields (and possible external/3th party value) calculations?

**Example with condition:**

I want to filter the results based on the average of 5 numeric fields. So i need to add them up and divide them by 5 and if that outcome \< 8 i do not want to use the entity.

**Example sort with external API value:**

I want to sort the results based on a calculation with an external API value. So lets say i have a numeric field in my entity with the value of 10. The external API gives me a value of 30. The calculation would be 30 - 10 = 20.

Now for my second entity the numeric field value equals 5 and the API sais 20. The calculation would be 20-5=15.

Now i want to sort the results from highest to lowest. So in this case the first entity should be first because the outcome of the calculation was 20 and for the second entity it was 15 so it should come second.

# Answer
> 0 votes
Some thoughts...

You should be able to do aggregation in your queries; try looking at `QueryAggregateInterface` and `ConditionAggregateInterface`. However this interface does seem to be pretty simple. The Views plugin implements full 'having' and 'group by' functionality, but probably in a way that's difficult to access outside views.

You might investigate using the Symfony Doctrine class or plain PDO to do it the 'old way'.

I am pretty sure you won't be able to calculate based on an external API; the database needs all the values to hand, either in a table or as query-provided data. Some databases do support advanced functionality like REST queries, but any code doing this won't be portable and so won't be available as standard in the Drupal interfaces.

You could possibly do the API lookups in advance (in e.g. php) and then pass them to a temporary table for the DB to check.

---
Tags: 8, entities
---