title: jQuery transition not run on anon page

text:
# Question
Title: jQuery transition not run on anon page
I am running Drupal 8.5.5 and am running into a problem. It seems for anonymous users jQuery is not loading a library that it would when I am logged in as admin. I tried to understand why that is but I am stumped. So far I disabled js caching, I have the following in my libraries.yml:

```
leadership:
   version: 1.x
   css:
     theme:
        css/leadership.css: {}
   js:
      js/leadership.js: {}
   dependencies:
      - core/jquery: {}

```

and it loads on the page, and runs this javascript which calls:

```
$content.toggleClass("whole-body", 800);

```

In the admin, I see the transitional effect of 800 seconds, but anonymous users don't see that.

# Answer
> 1 votes
I have figured it out, by just adding a bunch of jquery dependencies in my

> theme.libraries.yml

```
   js:
      js/leadership.js: {}
   dependencies:
    - core/jquery
    - core/jquery.once
    - core/jquery.ui
    - core/jquery.ui.widget
    - core/jquery.ui.draggable
    - core/jquery.ui.mouse
    - core/jquery.ui.position
    - core/jquery.ui.resizable

```

once of the jquery ui was missing.

---
Tags: javascript
---


title: Dispatch an Event when the a user logs

text:
# Question
Title: Dispatch an Event when the a user logs
I was looking into the new Events system for Drupal 8 and there's something I haven't been able to figure out.

I need to dispatch an event when a user logs something to the watchdog table using the new logging API.

```
// Logs a notice
\Drupal::logger('system')->notice($message);
// Logs an error
\Drupal::logger('system')->error($message);

```

https://www.drupal.org/docs/8/api/logging-api/overview

I already define a new Event in a custom module but I don't know what needs to be created so when a module logs/adds information to the watchdog table using the code above my event gets triggered.

Thanks

# Answer
> 1 votes
Once you get the event working, all you have to do is create an instance of the Logger Class in the Logger folder inside your module.

In here: /drupal\_root/web/module/custom/my\_module/src/Logger

And the class will be something like:

```
namespace Drupal\my_module\Logger;

use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;

class SendToEmail implements LoggerInterface {

  use RfcLoggerTrait;

  /**
   * Logs with an arbitrary level.
   *
   * @param mixed $level
   * @param string $message
   * @param array $context
   *
   * @return void
   */
  public function log($level, $message, array $context = []) {
    //Building the parameters for the email
    $params['level'] = $level;
    $params['message'] = $message;
    $params['context'] = $context;
    $this->sendEmail($params);
  }

  /**
   * @param array $params
   *
   * @return null
   */
  public function sendEmail($params = array()){
    //Variable declaration
    $module = 'my_module';
    $key = 'my_module_message';
    $to = "email@email.com";
    $from = "email@email.com";
    $language_code = \Drupal::service('language_manager')->getDefaultLanguage()->getId();
    $send_now = TRUE;

   $mail = \Drupal::service('plugin.manager.mail')->mail($module, $key, $to, $language_code, $params, $from, $send_now);
    return $mail;
  }
}

```

---
Tags: 8, event-subscribers
---


title: Running node creation from another url?

text:
# Question
Title: Running node creation from another url?
I have a node called "survey". To create one, you go to:

```
/node/add/survey

```

I want to make a new url at: /make-survey, which must show exactly what you would see at /node/add/survey

What is the easiest way to do this in Drupal 7?

**Follow up question:**

Once I got the paths right, I now need to change the title. Currently it is "Create Survey" ... i would prefer if it's just "Survey"

# Answer
Use the built-in aliasing built into the path module:

* Navigate to `/admin/config/search/path/add`
* Add `/node/add/survey` to **Existing system path**
* Add `/make-survey` to **Path alias**
* Click **Save**

The new `/make-survey` alias will now map to your survey add form.
> 3 votes

---
Tags: 7
---


# Question
Title: How can you filter out other languages Taxonomy Terms from an exposed filter?
I am working on a View for a content type which has a Taxonomy Term field. The vocabulary is setup with the Translation mode 'Translate'. The terms have all been translated so that the terms explicitly set Language (currently English and Spanish). The View has an exposed filter for this field and its showing both languages terms. How can I configure Drupal to only show the taxonomy terms for the current users language?

Relevant installed modules: Internationalization (i18n), Views translation (i18nviews), Taxonomy translation

I've read a lot of forums about how to get more languages terms to show, just not how to filter them out when you don't want to show them all.

# Answer
> 1 votes
It's a long time ago but I leave my comment here for anyone who came across this from Google. If you have installed "`i18nviews"` module, then you need to enable `Multilingual select (i18n_select)` module as well and your list will be filtered out based on the selected language.

---
Tags: 7, views, i18n-l10n
---


# Question
Title: How do you render a Node's Last Saved date in a Region Footer (ie, inside a Block on every page)?
I'm new to Drupal (8) and have no PHP experience, but I've managed to get this interesting CMS doing just about everything I need by playing with Twigs.

I cannot for the life of me figure out how to get a Page's "Last Saved" date to render in the footer block though.

In the Node twig I can add this, and it works perfectly:

```
{{ node.changed.value|date("d/m/Y H:i") }}

```

But in the region--footer.html.twig (which is an included block at the base of every page on the site, and where I wish to render this information) all I get back, from every combination I try, is the current date/time of when the page loads in the browser. Actually, i think it is the current server time.

Obviously there's something I just don't get about how Drupal works!

Can anyone offer a newbie some help in language I might understand?

Cheers, mrEdge

# Answer
I think you can add to the *yourtheme.theme* file next thinks;

```
function yourtheme_preprocess_region(&$vars) {
  $vars['node'] = \Drupal::routeMatch()->getParameter('node');
}

```

and afterwards in your twig template each region will have available variable `node`.

```
{% if node %}
  {{ node.changed.value|date("d/m/Y H:i") }}
{% endif %}

```

Don't forget to clear cache.
> 4 votes

---
Tags: blocks, datetime
---


# Question
Title: How to clear cache for config entity after making changes?
We have a custom form `mymoduleForm` that has `mymodule.settings` which stores some values that we need to run some logic when calling `mymodule_preprocess_node()` hook. The form just has a text area where we insert URIs and use that in the `mymodule_preprocess_node` hook to perform some action.

We can store the values in a Config entity as expected (see below). When we make changes to the Config entity, we want to clear cache for the config entity as well. How can we clear the Config Entity's Cache after making changes?

Goal:

* When there are updates to the Config entity, clear the cache for the entity so that the latest entity is used in `mymodule_preprocess_node` hook.

Issue:

* When we make changes to the Config entity using the custom form, the logic that we need to run is not running with the latest settings.

What we have tried:

1. Tried adding addCacheableDependency($form, $config); to the `buildForm()`, but it is not working.

**mymoduleForm.php**

```
class mymoduleForm extends ConfigFormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    if (!$this->entity->isNew()) {
        \Drupal::service('renderer')->addCacheableDependency($form, $this->entity);
      }

    $config = $this->config('mymodule.settings');

    $form['some_field'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Some field title'),
      '#description' => $this->t('some description'),
      '#default_value' => $config->get('some_field'),
    ];

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

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('mymodule.settings'),
      ->set('some_field', $form_state->getValue('some_fields'))
      ->save();
  }
}

```

**mymodule\_preprocess\_node**

```
function mymodule_preprocess_node(&$variables) {
  $config = \Drupal::config('mymodule.settings');
  $config_value = $config->get('some_field');

  $library = 'mymodule/some-library';

  if($config_value == 'some_value') {
    $variables['#attached']['library'][] = $library;
  }
}

```

# Answer
> 6 votes
Yes, you have to add the cacheable dependencies of the config object, not only to the form, but also to the render array in preprocess, so that the rendered output gets the correct cache data:

```
function mymodule_preprocess_node(&$variables) {
  $config = \Drupal::config('mymodule.settings');
  $config_value = $config->get('some_field');
  // add the cache tag, so that the output gets invalidated when the config is saved
  \Drupal::service('renderer')->addCacheableDependency($variables, $config);

  $library = 'mymodule/some-library';

  if($config_value == 'some_value') {
    $variables['#attached']['library'][] = $library;
  }
}

```

---
Tags: 8, entities, hooks, configuration
---


title: module controller does not respond!

text:
# Question
Title: module controller does not respond!
I'm trying to create a controller within my custom module, but the controller still doesn't response when visiting the associated path.

Here are my files:

### my\_module/my\_module.routing.yml:

```
my_module.agreement:
  path: 'my_module/send_consent'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::check_agreement'
    _title: 'Agreement controller'
  methods:  [GET]

```

### my\_module/src/Controller/MyModuleController.php :

```
namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyModuleController extends ControllerBase {

    public function check_agreement() {
        die('hello from controller');
    }
}

```

To test I visit `myproject.local/my_module/send_consent`

Any help?

# Answer
You forgot `requirements` (which is required):

```
my_module.agreement:
  path: 'my_module/send_consent'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::check_agreement'
    _title: 'Agreement controller'
  methods:  [GET]
  requirements:
    _permission: 'access content'

```

See Structure of roots for full details.
> 2 votes

---
Tags: page-controller
---


# Question
Title: How to check if an entity bundle has a field?
How can I check if a bundle has a field? I know I can use `$entity->hasField()` if I have a specific entity (as is defined in this post), but how can I get this info with just the entity\_type and bundle info?

I'm assuming I could just create an entity of the type and bundle (and never save it), and check against that, but that seems gross.

# Answer
Woops, this is closely related to Get all fields defined in a bundle, but since that gets all fields, I'll post this.

Use the EntityFieldManager (entity\_field.manager) service, specifically the getFieldDefinitions method, to get all field definitions, and then check for your specific field.

```
function doesBundleHaveField($entity_type = 'node', $bundle = 'page', $field_name = 'field_paragraphs') {
  $all_bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions($entity_type, $bundle);
  return isset($all_bundle_fields[$field_name]);
}

```
> 8 votes

# Answer
You can use static method loadByName from FieldStorageConfig, which will return field config entity if one exists for the provided field name, otherwise NULL. Then get the attached bundles and filter by your correspondent bundle:

```
use Drupal\field\Entity\FieldStorageConfig;
$field_storage = FieldStorageConfig::loadByName('node', 'field_foo');
if (!empty($field_storage) && in_array('page', $field_storage->getBundles())) {
  // TODO: Implement this.
}

```
> 4 votes

---
Tags: 8, entities
---


# Question
Title: How to use Services to create new node with Entity Reference field?
I am able to create a new node with body field, but when I try to set the value for my entity reference field, I get

> {"form\_errors":{"field\_drawing\]\[und":"An illegal choice has been detected. Please contact the site administrator."}}

I am sending a structure similar to the working body field, but with 'target\_id' instead of 'value':

```
'field_drawing' = {
    'und' = [
        0 = {
            'target_id' = 123
        }
    ]
}

```

123 is the nid of an existing node. What would cause an 'illegal choice' response?

# Answer
I figured out the solution from comments on this issue.

To set the field via services, you can set the field's widget type to "autocomplete" and instead of just sending the nid, send a string with the title of the referenced node, a space, and the nid inside parenthesis.

```
'field_drawing' = {
    'und' = [
        0 = {
            'target_id' = 'Title of Node (123)'
        }
    ]
}

```
> 4 votes

# Answer
In my case, an external script had to create nodes using json messages so I wanted to only pass the ids of the referenced nodes. to do this you have to switch the widget type to 'select list' and send the following:

```
'field_drawing':{
    'und':[123,124]
}

```
> 2 votes

# Answer
Just for reference.

I got problem with such data structure in my project, using entityreference field in Entityform entity.

This json fragment:

```
..."field_f_s_culture":{"und":[{"target_id":"... (336)"}]},...

```

triggers next error:

```
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '... (336)' for column 'field_f_s_culture_target_id' at row 1)

```

I was have to revert entityreference field structure to:

```
..."field_f_s_culture":{"und":[{"target_id":"336"}]},...

```

to get it work.
> 0 votes

---
Tags: 7, services, entities
---


title: Migration time created of node

text:
# Question
Title: Migration time created of node
I'm flowing article to migration my data. Every fields is working fine. But field **created** doesn't working. Field created always insert time import.

I try replace field created with setting

```
created:
  plugin: default_value
  default_value: 1389312000

```

but same result. **So how to migration time created of node?**

# Answer
Most likely your source plugin isn't supplying the `created` field to do what is done in the reference article:

`source:
 plugin: custom_article
destination:
 plugin: entity:node
 bundle: article
process:
 ...
 created: created`

This part of the source plugin config is saying, "import `article` nodes by setting its `created` field from the source column `created` generated by the `custom_article` plugin".

Adding:

```
created:
  plugin: default_value
  default_value: 1389312000

```

Is telling the migration to "set `created` to `1389312000` as a default (if there's no source plugin data"

If you're copying the reference article's `modules/migrate_custom/src/Plugin/migrate/source/Article.php`, you'll need to make sure your plugin's `query()` method is correctly querying its source so that's available for processing and

```
process:
  ...
  created: created

```

Is set in your migration config so that it's sourced correctly.
> 1 votes

---
Tags: 8, migrations
---


title: The missing phpmailer module

text:
# Question
Title: The missing phpmailer module
I updated a site with "Composer update --with-dependencies" and encountered the following problem:

```
User warning: The following module is missing from the file system: phpmailer in drupal_get_filename()

```

Then I ran: composer require drupal/phpmailer.

Terminal returned:

```
Using version ^3.0@beta for drupal/phpmailer
./composer.json has been updated

```

And

```
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files

```

But the Status Report still showed that phpmailer module was missing.

So I attempted running "drush en phpmailer -y"

And it returned:

```
phpmailer was not found.                                             [warning]
The following projects provide some or all of the extensions not     [ok]
found:
phpmailer
Would you like to download them? (y/n): y
This codebase is assembled with Composer instead of Drush. Use       [error]
`composer update` and `composer require` instead of `drush
pm-updatecode` and `drush pm-download`. You may override this error
by using the --pm-force option.
phpmailer was not found.                                             [warning]
Unable to download some or all of the extensions.                    [warning]
There were no extensions that could be enabled.                      [ok]

```

What can I do to fix this?

# Answer
There is a module for that: https://www.drupal.org/project/module\_missing\_message\_fixer

And you can try drush or devel according to the doc here https://www.drupal.org/node/2487215

Use Drush

```
drush sql-query "DELETE FROM key_value WHERE collection='system.schema' AND name='module_name';"

```

When done, clear the site's caches (e.g. drush cr). Also make sure that the CMI folder is cleansed of the broken uninstalled module. There may be some yml files left over and / or some system config. (this is all not the best way to do things as a FYI. However with Drupal 8 being so young, things don't go as planned always).

Use Devel

Enable Devel module and go to /devel/php. This will allow you to run some PHP code and you can execute the following:

```
$query = \Drupal::database()->delete('key_value')
    ->condition('collection', 'system.schema')
    ->condition('name', 'module_name')
    ->execute();

```
> -3 votes

---
Tags: 8, updating
---


# Question
Title: Customize output style of views filter fields
I have a view associated with many filter fields:

* Checkboxes
* Listboxes
* **Three date fields of textbox type.**

In admin theme(seven), the date filter fields aligned improperly and I would like to show the three date range filters aligned horizontally next to each other.

I couldn't add any class for filter fields from the admin UI.

Any help/ideas please?

# Answer
> 1 votes
The CSS classes given by Views should normally be good enough, if you don't know how to find them you may using a chrome or firefox browser: **right click** on the filter field and then **inspect element**

Or if you want you may install the Better exposed filters module and follow the intructions given in this question

**UPDATE:**

As per your comment below, **how to group filter fields under one div ?**, it is out of the scope of the original question and for that you will have to ask another question.

However, I believe that what you are asking for is not doable using the views UI and you will have to write your own custom codes, for that you may find the below links somehow useful even if they are referencing the D7 version:

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


# Question
Title: Edit a config variable of a custom module in controller
Is it possible to edit/create a config variable of a module in a controller created in the same module?

For example: module\_name/src/Controller/MyController.php:

```
class MyController extends ControllerBase {

    public function x($y) {
        $config = \Drupal::config('module_name.settings');
        $config->set('var1', $y)->save();
    }
}

```

**Update**:

module\_name.module:

```
function module_name_page_attachments(array &$page) {
  $config = \Drupal::config('module_name.settings');
  var_dump($config->get('var1'));
}

```

module\_name/config/install/module\_name.settings.yml:

```
var1: 0

```

module\_name/src/Form/moduleNameSettings.php:

```
class moduleNameSettings extends ConfigFormBase {

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

    public function submitForm(array &$form, FormStateInterface $form_state) {
        parent::submitForm($form, $form_state);
        $config = \Drupal::config('module_name.settings');

        $this->config('module_name.settings')
            ->set('var1', $config->get('var1'))
            ->save();
    }

```

# Answer
> 4 votes
With the ConfigFormBase, you need to implement the editableConfigNames() method. E.g.

```
  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'example.settings',
    ];
  }

```

In general, you need to get the editable version of the config file to change it. ConfigFormBase (well actually, ConfigFormBaseTraits) will only return the editable config is you implement the above method.

For reference, here's how you could do this without the ConfForm logic.

```
$config = \Drupal::service('config.factory')->getEditable('example.settings');
$config->set('message', 'Hi')->save();

```

See the documents for details.

Since you are expanding ConfigFormBase, you should be able to use:

```
$config = $this->configFactory()->getEditable('example.settings');

```

To get the editable version.

---
Tags: configuration, page-controller
---


# Question
Title: Composer package is updated, but core still asks to update
I am using Drupal 8.5.5. On admin/modules/update I red the following message.

Bootstrap (Theme)
Bootstrap (Theme) 8.x-3.11 update to 8.x-3.12 (Release notes)

The composer.json contains the following text.

```
"require": {
    ...
    "drush/drush": "^9.3",
    "drupal/core": "~8.5.3",
    "drupal/bootstrap": "^3.12"
},

```

I then ran `composer install` and installed Bootstrap 8.x-3.12. When I run `composer show drupal/bootstrap` it outputs the following.

```
name     : drupal/bootstrap
descrip. : Built to use Bootstrap, a sleek, intuitive, and powerful front-
end framework for faster and easier web development.
keywords :
versions : * 3.12.0
type     : drupal-theme
license  : GNU General Public License v2.0 only (GPL-2.0) (OSI approved)
https://spdx.org/licenses/GPL-2.0.html#licenseText
source   : [git] https://git.drupal.org/project/bootstrap 8.x-3.12
dist     : [zip] https://ftp.drupal.org/files/projects/bootstrap-8.x-3.12.zip 8.x-3.12
names    : drupal/bootstrap

requires
drupal/core ~8.0

```

When I go back to admin/modules/update Drupal still says Bootstrap 8.x-3.11 is installed. I have ran `drush updb` and `drush cr` to no avail. I am confused as to why it is not running composer's version of Bootstrap.

Why?

EDIT: When I run `drush pm:list --package bootstrap` the command line returns:

`Bootstrap (bootstrap) Enabled 8.x-3.11` . Yet composer's version is on 8.x-3.12.

# Answer
> 3 votes
**CREDIT TO @CGMonroe**

I had started since early stages of Drupal 8, so my themes folder was in

```
sites/default/theme/bootstrap
sites/default/theme/bootstrap_subtheme

```

but in composer.json, it updates in directory:

```
"installer-paths": {
  ...
  "themes/contrib/{$name}": ["type:drupal-theme"],

```

so what I needed to do was, move my /bootstrap\_subtheme from sites/default/theme to theme/ you should end up with:

```
theme/contrib/bootstrap
theme/custom/bootstrap_subtheme

```

and here is the correct way of configuring a theme/subtheme: https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme

---
Tags: updating, composer
---


title: Link translation for custom block

text:
# Question
Title: Link translation for custom block
I'm here

I need to create a link to three languages. for example

```
<div class="link">
  <div class="1_link">
    <a href="/en/link/1"> Link 1 </a>
  </div>
  <div class="2_link">
    <a href="/en/link/1"> Link 2 </a>
  </div>
  <div class="3_link">
    <a href="/en/link/1"> Link 3</a>
  </div>
</div>

```

other in Spanish

```
<div class="link">
  <div class="1_link">
    <a href="/pt-br/link/1"> Link 1 </a>
  </div>
  <div class="2_link">
    <a href="/pt-br/link/1"> Link 2 </a>
  </div>
  <div class="3_link">
    <a href="/pt-br/link/1"> Link 3</a>
  </div>
</div>

```

In Portuguez

```
<div class="link">
      <div class="1_link">
        <a href="/pt-br/link/1"> Link 1 </a>
      </div>
      <div class="2_link">
        <a href="/pt-br/link/1"> Link 2 </a>
      </div>
      <div class="3_link">
        <a href="/pt-br/link/1"> Link 3</a>
      </div>
    </div>

```

When I go to the block to see its links, by default it always appears / link / 1 no matter what language I am in.

It does not take in language: it ES or EN o PT-BR

Link 1 --\> hover url = http://url\_site/link/1 in any language.

should be

Link 1 --\> hover url = http://url\_site/en/link/1 OR Link 1 --\> hover url = http://url\_site/es/link/1 Link 1 --\> hover url = http://url\_site/pt-br/link/1

configuration of my block.

# Answer
> 1 votes
To do this for custom blocks, you will need to enable translations for blocks and custom blocks in the settings. Then you will need to create translations (with the correct links) for each language.

Details:

* Go to /admin/config/regional/content-language
* Make sure custom blocks is selected at the top.
* Save
* Scroll down to Custom Block section
* Make sure the basic block and at least the title and body fields are translatable.

To Edit the block.

* Go to the Custom Block library
* The Edit drop down should have a translate option
* Select this and in the translate screen, create a translation.
* Edit for the needed language.

Result is that if you are looking at a page for lang X and there is a lang X block translation. You will see this block.

---
Tags: 8, blocks
---


title: How do I send plaintext email?

text:
# Question
Title: How do I send plaintext email?
I've been using a combination of `drupal_mail()` and Mimemail to send out HTML formatted email; it's working fine. However, in some circumstances, I also need to be able to send out plaintext email, not an empty HTML template, but a completely raw, plaintext message.

I can't figure out how to disable Mimemail for these messages, while leaving Mimemail in place for the others.

How might I be able to do this?

# Answer
> 3 votes
I've spent some time trying to achieve the same goal. I didn't find a lot of documentation on MimeMail module, I inspected the code and found a solution :

```
  $message = drupal_mail('my_module', 'my_module_key', 'email@mail.com', $language,
    $params = array(
      'subject' => $subject,
      'plain' => TRUE,
      'plaintext' => $mailBody,
    ));

```

You just need to use `'plain' => TRUE` and put your mail content in `'plaintext' => $mailBody`

# Answer
> 0 votes
Figured it out, I think:

(1) For some module, create a mail template to handle the plaintext requests, the details of which depend on how you're putting together your messages. For me, this works:

```
function mymodule_mail($key, &$message, $params) {
     switch ($key) {
          ...
          case 'plaintext':
               $message['subject'] = $params['message_header'];
               $message['body'] = $params['message_body'];
               break;
     }
}

```

(2) Use `mailsystem_set` to set up an entry in the `mail_system` variable that points to the combined module and the key -- `mymodule_plaintext` in this case -- and that specifies the mail system DefaultMailSystem:

```
  module_load_include('module', 'mailsystem');
  mailsystem_set(
    array(
      'vr_random_plaintext' => 'DefaultMailSystem',
    )
  );

```

(See `mimemail.module` for tips on doing this; since it only needs to be run once, they recommend doing it in a `hook_enable` handler.)

(3) You should then be able to send plaintext messages by calling `drupal_mail()` and specifying `mymodule` and `plaintext` as the module and mail\_template for the message.

This is working for me, although I may have glossed over a thing or two. If there are questions, post away...

---
Tags: 7, mimemail
---


# Question
Title: How do I build the node title from field values when saving the node?
I have a content type (*supertest*) with the *Category* and *Section* fields, which are taxonomy term references. Every user has a *Display name* field.
I need to update the node titles when saving the nodes using *\[category\] - \[section\]: \[author.display\_name\]* as format.

I've tried to add a rule, *Display message* action (just to test) on *Before content save* event, but it doesn't work. I can't figure out how to use the category field value to set the node title.

How can I make rules to change the node title?

# Answer
The answer is very easy to accomplish by just following the below steps.

First of all, with all my respect to the glory of the Rules modules but yet it is not ready for development on Drupal 8 Website otherwise you will be facing tons of issues and you will spend most of your time within the issue page.

So, here comes the Business rules, the alternative workflowing D8 module.

**What is Business rules module:**

> The Business Rules module is inspired on Rules module and allow site administrators to define conditionally actions execution based on events. It's based on variables and completely build for Drupal 8.
> This module has a fully featured user interface to completely allow the site administrator to understand and create the site business rules. It's also possible to extend it by creating new ReactsOn Events, Variables, Actions and Conditions via plugins.

I strongly advice you to read the **documentation**, so you get more familiar with it.

**Why using Business rules modules ?**

Business rules modules will not only help you to achieve your above question but will give your website a powerful way to execute **actions** based on **events and conditions** defined by you as administrator.

Using and getting familiar with such great module, will save you spending time trying to create a custom module to add some extra features to your website while you can do it with few clicks using **Business Rules** modules.

**How to auto-generate the title based on node's fields values after saving the node:**

1) Install and Enable the:

* Business rules Module.
* Dbug Module. (Dependency for business rules module)
* Token Module. (Specific for your case)

2) Goto: `/admin/config/workflow/business_rules/collection`

3) Under the **Actions** Tab, Click on **+Add Action**

4) **Type:** Set Field Value

5) Here is where the magic will happen: \- **Label:** Change the Title field based on other field values.

* **Description:** Action to Change the Title field based on other field values.
* **Target Entity Type:** Content
* **Target Bundle:** Supertest
* **Field:** Text (Plain): Title \[Title\]
* **Value:** `[node:category:entity:name] - [node:section:entity:name] - [node:author]`
* Save the action

6) Goto: `/admin/config/workflow/business_rules/collection`

7) Under the **Rules** Tab, Click on **+Add Rule**

8) **Reacts on event:** Before Saving Entity

* **Label:** Before saving entity of type node (supertest)
* **Description:** Before saving entity of type node (supertest)
* **Target Entity Type:** Content
* **Target Bundle:** Supertest
* **In the Items Section:** Click on **add action** link.
* **Popup window will open:** Click on the desired action's title to add it to your current rule. (In your case, there is only one action available so click on its title)
* Save the Rule

**Testing the rule:**

1) Goto: `/node/add/superset`

2) **Title:** This title should change after saving this node

3) Set your taxonomy fields as desired

4) Save the node.

5) Check your new title.

Voila!

Feel free to ask for help if you faced some troubles.
> -3 votes

# Answer
Could be a job for Automatic Entity Label. Actually I'm using it that way – in production (though it has no stable release yet it works just fine).

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

You can define tokens from which the title will be built. An you can optionally set the title field to be always hidden on the node form. I'd also recommend to make the fields mandatory (required) that you use to build the title.
> 4 votes

---
Tags: 8, nodes, rules
---


# Question
Title: Is the "size" field in file_managed used for anything?
I'm having to import videos and video thumbnails manually to the file\_managed table since there is no migrate support for it yet.

I'm wondering if the size is really used for anything?

# Answer
> 5 votes
It's used in a few places:

It's probably a good idea to fill this field in if you're able, or at least run a small script to do so after you've manually entered the records. Something like this maybe:

```
// The filesize column defaults to 0 so it's an easy check.
$fids = db_query('SELECT fid FROM {file_managed} WHERE filesize = 0')->fetchCol();

// Loop through the files and update the file size field.
foreach (file_load_multiple($fids) as $file) {
  $file->filesize = filesize($file->uri);
  file_save($file);
}

```

# Answer
> 3 votes
Another use for the `filesize` column is with Views. If you create a view over a content type with filefields, you can create a relationship to the `fid`. When you do this, a **File** group appears in the fields. One of the new fields is **File: Size**. Very handy when you make a list of downloads attached to a node.

# Answer
> 0 votes
DRUPAL 8

Updated version of the above

```
// The filesize column defaults to 0 so it"s an easy check.
$fids = db_query("SELECT fid FROM {file_managed} WHERE filesize > 0")->fetchCol();

// Loop through the files and update the file size field.
foreach (file_load_multiple($fids) as $file) {
 echo $file->getSize(). " ";
 $uri = $file->getFileUri();
 $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager')->getViaUri($uri);
 $file_path = $stream_wrapper_manager->realpath();
 $file->setSize(filesize($file_path));
 $file->save();
}

```

I use it with *drush php-eval '...'*

---
Tags: 7, files
---


title: Direct photo and name to Profile page

text:
# Question
Title: Direct photo and name to Profile page
**Update#2**

Actual user name is `superuser` but with kint, its still reading the admin `id` and `displayname`. This also happens to the URL, its reading the admin's profile link `profile/1`

I tried to dig into `{{ content }}` but cannot find tag with value `superuser`.

---

**Update:**

I noticed that in my twig template, `{{ content.user_id }}` would link into user's profile page(`user/1`), so the main question I think is what is the correct profile id of user in twig. I tried using `content.profile_id` but doesn't work.

---

I have this simple site that a user can post a simple content in the site. I also have a custom Profile type enabled from Profile module. I noticed that when I click on the photo, it is directed to the profile page `profile/1`(which is my expected result) but when the author name is clicked, it is directed into the user's profile page `user/1`. How can I change the author's name link to be directed into profile page`profile/1`?

# Answer
You can use the example from Twig Functions:

> ```
> {# Link to user entity page. #}
> <a href="{{ path('entity.user.canonical', {'user': user.id}) }}">{{ 'View user profile'|t }}</a>
>
> ```

and modify the route to point the link to the profile page:

```
{# Link to user profile page. #}
<a href="{{ path('entity.profile.canonical', {'profile': user.id}) }}">{{ 'View user profile'|t }}</a>

```
> 2 votes

---
Tags: 8, theming, users
---


# Question
Title: Remove Configuration Management Destination
I'm using `drush cex` or `drush cim` to export and import configuration on D8 site.

Every time I run those commands, I get asked a question to select option for cancel, sync or staging, which is quiet annoying.

Is there a way to remove staging destination and only use sync so that I can use `drush cex -y` or `drush cim -y` without errors?

# Answer
> 1 votes
Check please the arguments: https://drushcommands.com/drush-8x/config/config-export. You can use directly `sync` in your command

```
   drush cex sync -y

```

# Answer
> 0 votes
Please check your **$config\_directories** in your settings.php and remove staging there

Besides, you can use Configs Split ( when you have different configurations for your available environments ) and set active one in settings.php

---
Tags: 8, drush, configuration
---


# Question
Title: How to add content inbetween node fields on node creation?
I have a node called survey. Inbetween fields I want arbitrary text. The text is not associated with a field. I tried adding a "group", but could not find a way to add html. Then I looked at adding some kind of plain text field, but also no luck.

I'm sure I've done this using groups in the past, but I just can't seem to find out where to do it. Any ideas?

And just to be clear: \- I have a node called survey \- It has fields on it like "name" and "email" address \- Inbetween name and email, I want, for example, to show an image and some text. I want to be able to enter the html to do this, but not sure how to add it?

In code, I would just add a type "#markup", but how do you do this via the interface?

# Answer
I guess this inbetween content is static or else you would have it as a field as well. So, I think you should just edit the template file of this node and add the fields and whatever other info you want between them directly on the file.

It would look sth like:

```
<?php print render($content['field_firstfield']);?> // first custom field
<div>
whatever you want inbetween
</div>
<?php print render($content['field_firstfield']); ?> // second custom field
<?php print render($content['body']);?> // all the rest content

```
> 0 votes

# Answer
Field help helper

> The Field help helper module adds a link to entity configurable fields so that users with the appropriate permissions may easily edit the help text and label for a field in context of where the field displays.

Better field descriptions

> Better field descriptions makes it possible to add themeable descriptions to fields in forms.

Field Help

> This module is a container for functions that extend Drupal's core Field API. It could be installed as a library and it would work just as well.

I hope the above modules will give you what you are asking for.

**Another Workaround:** If i understand your question, you may use a long text field (same as the body field), make it read-only (disable it), change its settings to **full html**, and put inside whatever html code (image, text...) you like.

Note: if you have the **ckeditor** (wysiwyg editor bar) installed, it will be a better way for you to just *you know lets say decorate* your text.
> 0 votes

# Answer
Markup is undeniably the module for the job.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Using Highlight Module with Default Search Module
I'm trying to use this highlight module to highlight search terms on my site but can't seem to get it to work. I'm using Drupal 7, the basic search module that comes with Drupal, and Views to display the search interface (and results).

I *think* the main issue has to do with inputting a correct JavaScript syntax (regex) for local searches but the example given in the screenshot on the module page (linked above) only shows regex for apache solr and I'm wondering if anyone know what I should use for the default search, or if its even possible?

**Note: I've already changed the 'Highlight area' option on the highlight module configuration page to .search (which is the body class for my search view).**

# Answer
I think, looking at the examples, that something like this expression should work if you have clean URLs turned on and searches have URLs like http://example.com/search/node/keywords.

```
\/search\/node\/([^?#]+)

```

But I have never used this module and it looks a bit ropey. You can test your own regular expressions at https://regex101.com/ (use JavaScript mode). Contrary to the examples you should not need to include the domain of your site in the search patterns.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Error Passing Extra Parameter to Custom Form
I have a simple custom form that works until I try to add a custom parameter for my module called "forms\_admin".

These are the contents of my **forms\_admin.routing.yml**

```
forms_admin.settings:
  path: 'admin/config/system/forms/{arg1}'
  defaults:
    _form: '\Drupal\forms_admin\Form\FormSettings'
    _title: 'Forms Settings'
  requirements:
    _permission: 'access content'

```

This is a relevant part of my **FormSettings.php** file (Currently do not have any custom Validation or Submit actions)

```
public function buildForm(array $form, FormStateInterface $form_state, $arg1 = NULL) {
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Title'),
      '#required' => TRUE,
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );

return $form;
}

```

And my third file is: **forms\_admin.links.menu.yml**

```
forms_admin.config:
  title: Forms
  route_name: forms_admin.settings
  parent: system.admin_config_system
  description: 'Forms settings'
  weight: 0

```

The moment that I add `{arg1}` to my **forms\_admin.routing.yml** and `, $arg1 = NULL` to my **FormSettings.php** file, I am unable to acces the website.

---

I receive a white page with the error that states:

> The website encountered an unexpected error. Please try again later.

After removing `arg1` from my two files and going to the Recent Log messages, this is the error I receive:

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("arg1") to generate a URL for route "forms\_admin.settings". in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 182 of /var/www/test\_site/docroot/core/lib/Drupal/Core/Routing/UrlGenerator.php).

---

I have tried changing arg1 to other names, not making $arg1 = NULL, etc. and I receive an error every time.

What am I missing?

# Answer
The problem is that your FormSettings class is not the controller in this case. It's the controller method which is where the routing system expects $arg\_1.

I think you need to define your own controller which accepts the request and passes the argument to the form. Extending the core Drupal\Core\Controller\FormController class is probably the simplest way forward.
> -1 votes

---
Tags: 8, forms
---


# Question
Title: Drush tries to export config for modules I deleted months ago
I'm using Drush 9.3 and when I export config it wants to create config files for modules that have been gone for months. One of those is plupload which is nice because it's easy to search the code base to see if I have anything that references plupload whatsoever. I do not. Yet when I run "Drush cex" it exports plupload.settings as well as settings for several other modules that are LONG GONE. When I try to "Drush cim" on the staging server the import fails complaining that these modules do not exist. I'm sure these modules are in fact referenced in the drupal database but I cannot figure out anywhere in the GUI to remove them, no option to uninstall Plupload from the uninstall page. If I do install plupload using composer it appears as a module that can be enabled under the modules page, but still no option to uninstall or remove from the Drupal database. What am I missing? Why does Drupal think I still have these modules?

Thank you!!!

# Answer
> 0 votes
When you removed the modules I would guess you didn't uninstall them first. The simplest approach is probably going to be to put the code back by whatever means you originally installed them, in the same location, then uninstall them via the admin panel or drush before removing the code again. That way the core code will fire that deletes the config.

It is possible that a module may break the uninstall process, in which case this is a trickier problem but best to go down the simplest route first.

---
Tags: drush, importing-exporting
---


# Question
Title: Drupal Commons, can't break-contact error
I am using Drupal Commons (7.x-3.46).. Whenever trying to "break contact" of a trusted-contacts, I get an error:

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /batch?id=19&op=do StatusText: Service unavailable (with message) ResponseText: EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at og\_membership(): . in EntityDrupalWrapper-\>set() (line 756 of C:\Users\USER\Sites\commons-7.x-3.46or\profiles\commons\modules\contrib\entity\includes\entity.wrapper.inc).

An authenticated user can't break-contact at all. Trying as an administrator, it throws the error, but does complete the operation, and does breaks the contact. This seems (to me) to be a crucial issue. If users can't remove a contact, I dare-not give them the possibility to add contacts in the first place..

At some point I thought it was all about VBO, so (I think) I uploaded the dev version of it, but I'm still getting the same behavior. Also, changing the php version as suggested somewhere, made no difference.

In my search for a solution I've come across many similar issues, some of which I've listed below. But I haven't found the very same issue I'm facing, and with so many different solutions I'm not sure where to start. In some posts it's about views-bulk-operations. In others it's about the Entity module. Or about Organic Groups. Or indeed about the Trusted-Contacts module itself. As I'm no patching-guru, I'm uncertain of how to proceed

Similar but not identical issues:

# Answer
to resolve this problem, two patches are needed:

1 patch for the trusted contacts module as discussed in comment #2 here: https://www.drupal.org/project/commons/issues/2588155

2... and a patch for the membership-delete-action .../profiles/commons/modules/contrib/og/includes/actions/membership\_delete.action.inc as discussed here https://www.drupal.org/project/opigno\_lms/issues/2953675

works for me... d
> 0 votes

---
Tags: 7, users, debugging
---


# Question
Title: Field help text is printed as input field title, not in separate field
On Bootstrap theme add field Text, give it any Help text, save it and you get empty field, but if you hover on the field it shows the help text on mouse tooltip.

But if you e.g. make list field (text) and give it help text, it gets printed in separate `help-block` div under the field. How do I get that for Text fields or all/any fields?

# Answer
Try to uncheck 'Smart form descriptions (via Tooltips)' in Appearance -\> Bootstrap settings -\> General -\> Forms.
> 1 votes

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


# Question
Title: with BEF collapse expand items under their parent
How to collapse and expand items under their parent using better exposed filter and Nested Checkboxes .. What i mean ...that all the child items to be collapsed and they expand when the user click on (+ e.g) for the parent or check the parent box. I am making a car dealer website and i need that to make an advanced search. Any help will be appreciated.

# Answer
I fixed this issue and here is the solution for any one want to do the same, based on this conversion Collapse and Expand according to Hierarchy

add this code to your theme and you can use this module to add Javascript or CSS through the views page or block Code per Views Display

This code will add a + button beside the every parent, which will expand the checkboxes when clicked

```
(function ($) {
Drupal.behaviors.betterExposedFiltersExpandCollapseNested = {
attach:function (context, settings) {
  if (!('$befSetupDone' in window)) {
    $('ul.bef-tree-child.bef-tree-depth-1').css('display', 'none');
    var $expander = $('<span class="expander">+</span>');
    $('ul.bef-tree-child > li:has(ul) > div.form-item').prepend($expander);
    $('.expander')
      .click(function() {
        $ul = $(this).parents('li:first').find('ul');
        $ul.toggle('fast');
     })
    $befSetupDone = 1;
  }
 }
 }
 }) (jQuery);

```

---

and another code which will expand when the parent checkbox checked

```
(function ($) {
Drupal.behaviors.betterExposedFiltersExpandCollapseNested = {
attach:function (context, settings) {
  // first collapse the children
  $('ul.bef-tree-child.bef-tree-depth-1').css('display', 'none');
  $('.form-checkboxes.bef-select-all-none li').has('ul').once('bef-tree', function () {
    $(this)
      .find('input.form-checkboxes:first')
      .click(function() {
        $ul = $(this).parents('li:first').find('ul');
        if($(this).attr('checked')) {
          $ul.slideDown('fast');
        }
        else {
          $ul.slideUp('fast');
        }
      })
   });
  }
 }
}) (jQuery);

```

Note: You will have to choose (Nested Checkboxex/Radio Buttons) and check this option in better exposed filter

> Add select all/none links

---
> 1 votes

# Answer
Based on the code from Ahmed Hassan, I added functionality:

1. keyboard navigation
2. checkbox hidden on parent nodes
3. aria, labels and other accessibility functionality

```
/**
 * @file store_better_exposed_filters_expand.js
 *
 * Provides some client-side functionality for the Better Exposed Filters expand/collapse of taxonomy terms
 *
 * Kevin Finkenbinder
 * Added keyboard interface, aria labels and functionality, removed checkbox in front of parent nodes
 * Based on the work of Ahmed Hassan (https://drupal.stackexchange.com/a/109214/19071)
 */
(function ($)
{
  Drupal.behaviors.betterExposedFiltersExpandCollapseNested = {
    attach: function (context, settings)
    {
      if (!('$befSetupDone' in window))
      {
        $('bef-tree').attr('role', 'tree');
        $('bef-tree-child').attr('role', 'treeitem');
        $('bef-tree-child ul').attr('role', 'group');
        $('bef-tree-child li').attr('role,treeitem');
        $('ul.bef-tree-child.bef-tree-depth-1').css('display', 'none');
        $('.bef-tree-child input').attr('tabindex', -1);
        var $expander = $('<span tabindex=-1 class="expander">+</span>');
        $('ul.bef-tree > li:has(ul) > div.form-item').prepend($expander);
        $('ul.bef-tree-child > li:has(ul) > div.form-item').prepend($expander);
        $('.expander').each(function (index)
        {
          $(this).attr('id', $(this).next().attr('id'));
        });
        $('ul.bef-tree > li:has(ul) > div.form-item > input ').remove();
        $('ul.bef-tree-child > li:has(ul) > div.form-item > input').remove();
        $('.expander').first().attr('tabindex', 0); /* tab to control but not individual elements - see accesssibleculture.org/articles/2013/02/not-so-simple-aria-tree-views-and-screen-readers/ */
        $('ul.bef-tree-child.bef-tree-depth-1').css('display', 'none');
        $('ul.bef-tree-child').css('list-style-type', 'none');
        $('ul.bef-tree').css('list-style-type', 'none');
        $('.expander').css('cursor', 'pointer');
        $('.expander').on('click keydown', function (event)
        {
          if (event.which == 32 || event.which == 13 || event.which==1) /*spacebar,enter or mouse click*/
          {
            $ul = $(this).parents('li:first').find('ul');
            $ul.toggle('fast');
            event.preventDefault();
            return false;
          }
          else if (event.which == 37) /*left arrow */
          {
            if ($(this).parents('li:first').find('ul').is(":visible"))
            {
              $(this).parents('li:first').find('ul').hide();
              event.preventDefault();
              return false;
            }
          }
          else if (event.which == 38) /*up arrow */
          {
            if (!$(this).closest("li").is(':first-of-type'))
            {
              if ($(this).closest("li").prev().find('ul').is(':visible'))
              {
                $(this).closest("li").prev().find("ul li:last div input:checkbox").focus();
              }
              else
              {
                $(this).closest("li").prev().find(".expander").focus();
              }
              event.preventDefault();
              return false;
            }
          }
          else if (event.which == 39) /*right arrow */
          {
            if ($(this).parents('li:first').find('ul').is(":visible"))
            {
              $(this).parents('li:first').find('ul input').first().focus();
              event.preventDefault();
              return false;
            }
            else
            {
              $(this).parents('li:first').find('ul').show();
              event.preventDefault();
              return false;
            }
          }
          else if (event.which == 40) /*down arrow */
          {
            if ($(this).closest('li').find('ul').is(':visible'))
            {
              $(this).closest('li').find('ul li:first div input:checkbox').focus();
            }
            else if (!$(this).closest("li").is(':last-of-type'))
            {
              $(this).closest("li").next().find(".expander").focus();
              event.preventDefault();
              return false;
            }
          }
        });
        $('.bef-tree input:checkbox').on('keydown', function (event)
        {
          if (event.which == 37) /*left arrow */
          {
            $(this).parents('li:eq(1)').find('.expander').first().focus();
            event.preventDefault();
            return false;
          }
          else if (event.which == 38) /*up arrow */
          {
            if ($(this).closest('li').is(":first-child"))
            {
              $(this).parents('li:eq(1)').find('.expander').first().focus();
            }
            else
            {
              $(this).closest('li').prev('li').find(':checkbox').focus();
            }
            event.preventDefault();
            return false;
          }
          else if (event.which == 40) /*down arrow */
          {
            if ($(this).closest('li').is(":last-child") && !$.isEmptyObject($(this).parents('li:eq(1)').next().find('.expander')))
            {
              $(this).parents('li:eq(1)').next().find('.expander').focus();
            }
            else
            {
              $(this).closest('li').next().find(':checkbox').focus();
            }
            event.preventDefault();
            return false;
          }
        });
        $befSetupDone = 1;
      }
    }
  }
})(jQuery);

```
> 0 votes

# Answer
Here is what I used to output the field in a hierarchy. Note, I include this using Display Suite Code Fields, but it could easily be placed in a module.

```
<?php

function map_leaves($term_parents, &$term_tree, $depth = 0) {
  if (!isset($term_tree[$term_parents[$depth]->name])) {
    $term_tree[$term_parents[$depth]->name] = NULL;
  }
  if ($depth < count($term_parents) - 1) {
    map_leaves($term_parents, $term_tree[$term_parents[$depth]->name],$depth + 1);
  }
}

function output_term_tree($term_tree) {
  $return = '<ul class=msul_3';
  $return .= 'style="column-count:3;-webkit-column-count:3;-moz-column-count: 3;"';
  $return .= '>' . PHP_EOL;
  foreach ($term_tree as $term_name => $children) {
    $return .= '<li class="field-items">' . PHP_EOL . $term_name . PHP_EOL;
    if (!empty($children)) {
      $return .= output_term_tree($children);
    }
    $return .= '</li>' . PHP_EOL;
  }
  $return .= '</ul>' . PHP_EOL;
  return $return;
}

$node = node_load(explode('/', $_GET['q'])[1]);

$terms = $node->field_library_space_equipment['und'];
$term_tree = [];
if (!empty($terms)) {
  foreach ($terms as $term) {
    $term_parents = array_reverse(taxonomy_get_parents_all($term['tid']));
    map_leaves($term_parents, $term_tree);
  }
}
unset($term_tree['Space Location'], $term_tree['Space Types']);
$return = output_term_tree($term_tree);
echo $return;
?>

```
> 0 votes

---
Tags: javascript, theming, views
---


title: Modal delete confirmation

text:
# Question
Title: Modal delete confirmation
How do I get a confirmation message to show as a modal dialog?

```
$form['mytable'][$id]['operations']['delete'] = array(
  '#type' => 'submit',
  '#value' => t('Delete'),
  '#name' => 'd' . $entity->ref,
  '#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}'),
);

```

I've looked at the Colourbox module and `OpenModalDialogCommand` but I don't know how to integrate this into `#attributes`.

# Answer
> 1 votes
See https://www.drupal.org/node/2253257, wich would do this by default.

It's pretty easy to do it for your own link, note that the patch there is out of date. Instead of the accepts thing, you simply put data-dialog-type and data-dialog-options on your link attributes. See also https://www.drupal.org/node/2488192 that describes this change and contains lots of examples.

# Answer
> 1 votes
First, add the dependency:

```
js:
  js/module.js: {}
dependencies:
  - core/jquery
  - core/jquery-ui
  - core/drupal.dialog.ajax

```

Second, add the `use-ajax` class to the link:

```
$form["menu"] = array(
  "#type" => "link",
  "#title" => "Ajouter un menu",
  "#url" => Url::fromRoute("sallamand.footer_menu.add"),
  "#attributes" => [
     "class" => array("use-ajax"),
  ],
);

```

---
Tags: 8, forms
---


# Question
Title: How can I set the view mode of a node through rules
I'd like to change the view mode of a node based on the role of a user and another flag in the node, and by using the Rules module.

Since a call to display the node by default is full content, I wrote a rule that on **Content is Viewed** for that node type, it then checks the conditions and sets data value view-mode to teaser.

However, even when the conditions are met properly the node still displays full text.

From this I am assuming that Content is Viewed is being executed after rendering or am I missing something in my approach?

# Answer
What "Content is viewed" actually means, seems to be like so:

* The event ***Content is viewed*** is what it is: the user has (already) started viewing the content.
* The (system) event ***Drupal is initializing*** is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" **BEFORE** the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to How to specify a Rules event like "Content is 'going to be' viewed"?

**Be aware**: this applies to D7 ... and D6 is another story (from the question context I'm not sure if this is fopr D6 or D7 ...).
> 1 votes

# Answer
For such a simple task don't use Rules. Or any other dependency-heavy module. Getting to the root of your problem, you want to switch the view mode depending on some custom logic. Then all you need is one small snippet placed in a basic custom module: `hook_entity_view_mode_alter()`.

> Change the view mode of an entity that is being displayed.

You can easily add any custom logic inside this sample code:

```
function hook_entity_view_mode_alter(&$view_mode, $context) {

  // Render node in a different view mode when accessed as teaser.
  if ($context['entity_type'] == 'node' && $view_mode == 'teaser') {
    $view_mode = 'teaser_foo';
  }
}

```
> 1 votes

# Answer
You might alternatively try the combination of Display Suite and Contextual View Modes (for setting the view mode) and Context (for getting the condition) modules. Obviously this is an overkill for what you and me want to achieve plus for some reason Contextual View Modes doesn't work for me right as I'm getting errors.

If you manage to use rules, please make sure to share the rule you wrote to change the view mode!

**Edit**: OK this setup actually does work very well and the errors don't interfere with functionality. Regarding your specific problem (I know it's a lot of modules but what the hell):

* Install Display Suite, Contextual View Mode, Context
* Set up your custom view modes with display suite
* Add invisible taxonomy term to content type
* Make rules trigger a term change in that taxonomy field when node is flagged (this is needed because context module doesn't listen to flags - the sandbox modules intended for that don't work for me either)
* Create a taxonomy and user role context (as per your requirements)
* Set up Contextual View Modes module (see module page for instructions)

This should work.

BTW I was using the latest development releases.
> -1 votes

# Answer
This isn't good for performance I guess but try changing the view mode using the rule, then force entity save and redirect to the page again..

I'd consider the other solutions given here or panels with different variants.
> -1 votes

---
Tags: rules, entities
---


# Question
Title: How to change display modes per node (view modes)?
In Drupal 8 views modes are supported by core, which makes the Entity view modes module obsolete. I will like to have the ability to change my view mode per node without using the Display Suite module.

Does anyone know if I can do this by only using Drupal core or a module that is lighter than *Display Suite* module?

Ideally, I would like to have a select list to pick my view mode at the node level.

# Answer
> 7 votes
I've used the View Mode Selector module in Drupal 7 for exactly that purpose. I haven't tried it in Drupal 8, but it has an 8.x-1.0-beta1 release created on June 16, 2020.

# Answer
> 16 votes
That's a task for `hook_entity_view_mode_alter()`.

> Change the view mode of an entity that is being displayed.

See the following working sample that automatically lets the node whose ID is 123 be rendered in the *teaser* view mode when accessed as full page. You could simply add your own logic (type, user, datetime etc.) as well.

```
/**
 * Implements hook_entity_view_mode_alter().
 */
function MYMODULE_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {

  // Change the view mode to teaser on full page view for node ID 123.
  if ($entity->getEntityTypeId() == 'node' && $entity->id() == '123' && $view_mode == 'full') {
    $view_mode = 'teaser';
  }
}

```

As you can maybe imagine, from `$entity` you can get any field value of a node. You could also add some select list field or taxonomy reference to your content type and then adjust that value node-wise. Finally you can use above code snippet to switch the view mode depending on these values. Mission accomplished.

# Answer
> 4 votes
**Edit**: just realised original post said **without** using Display Suite. Will leave answer here anyway should it be useful to others, who came across this question and may wish to know how it's done with Display Suite.

Another options which is available is to use the Display Suite module. I would be tempted to use this over the View Mode Selector module, which does not yet have a stable release. By using Display Suite you will not only be dealing with a stable module, but will also be covered by Drupal's security policy which only applies to stable module releases (alpha, beta and dev modules are not covered).

To switch display modes on individual nodes you need to:

1. Install the `Display Suite` and `Display Suite Switch View Mode` modules, both of which are included in the Display Suite module package.

2. Go to the edit page for the content/node you want to change. On the edit form will be a tab called `Display settings`. Inside this tab you can select the display mode to use for this node.

For a more comprehensive description of this process see: Using Display Suite in Drupal 8: How to Use Switch View Mode Sub-module

# Answer
> 2 votes
To define a view mode per content type (nodes types) is simple, Drupal 8 already can do that.

Go to Structure -\> Content type -\> Manage Display

If you want just one view mode for your node (I mean, all nodes of a particular type render in the same way), just use only the default view mode and mange how it will display. The image below shows a screen with more explanation.

# Answer
> 0 votes
This is similar to Drupal 7. You will want to use template\_preprocess\_node() to change the view mode before rendering.

```
<?php

/**
 * Implements template_preprocess_node()
 **/
function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  // Check if a field that lists view modes is asking for
  // a different one than currently set. If it is, change it.
  // There is a D7 module that might be ported to D8:
  // https://www.drupal.org/project/view_mode_field

  $variables['#element']['#view_mode'] = 'teaser';
  $variables['view_mode'] = 'teaser';

  // might need to rework other node variables
  $variables['teaser'] = true;
}
?>

```

---
Tags: 8, nodes
---


title: Updating manually with CPanel

text:
# Question
Title: Updating manually with CPanel
I've updated my local site with composer. Now I'm trying to update the production one:

1. Go to Cpanel.
2. On my local computer, take the local web folder and delete in it all 1-level files that are non-folders, and the sites folder.
3. Make a zip archive from the rest of the folders and upload it production (delete the invisible files too).
4. Delete on production all folders except the sites folder into trash.
5. Unzip the uploaded archive.
6. Change permissions for the uploaded folders:

> find /home/zb/public\_html/core -type d -exec chmod 755 {} \\; find /home/zb/public\_html/libraries -type d -exec chmod 755 {} \\; find /home/zb/public\_html/modules -type d -exec chmod 755 {} \\; find /home/zb/public\_html/profiles -type d -exec chmod 755 {} \\; find /home/zb/public\_html/themes -type d -exec chmod 755 {} \\; find /home/zb/public\_html/vendor -type d -exec chmod 755 {} \\;

7. Reload the production site and it says that it encountered an unexpected error.

I've looked at error\_log file and saw this:

> Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "Field uses\_legacy\_adjustments is unknown." at /home/zb/public\_html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php line 829

What do I do wrong? How to make the site work?

# Answer
> 0 votes
I should've compressed the updated index.php file and extracted it into the root directory as well and changed permissions of that file to 644. After I had done that the error disappeared and the site started working fine. Then I updated the database.

---
Tags: 8, updating
---


title: Get paragraph delta/weight in template

text:
# Question
Title: Get paragraph delta/weight in template
I have defined a paragraph type that has a text field and an image field. At the moment the twig template is something like this

```
<div class='paragraph_wrapper'>
  <div class='text-container'>{{ content.field_text }}</div>
  <div class='image-container'>{{ content.field_image }}</div>
</div>

```

The problem is I want to alternate the positions of the text & image containers for each paragraph. For example the first one would have text then the image, the next would have the image then the text and so on.

How do I get the paragraph template to be aware of its order in the list? If I use a preprocess function how do I get the order than pass the value as a variable to Twig?

# Answer
I'm not sure what template you're using, and I'm not sure how your site is setup. But if you have a template that is looping through and displaying these paragraphs, you can add a check in your twig file that checks if the paragraph is even or odd.

```
{% for paragraph in paragraphs %}
    {% if loop.index is divisibleby(2) %}
        <div class='text-container'>{{ paragraph.field_text }}</div>
        <div class='image-container'>{{ paragraph.field_image }}</div>
    {% else %}
        <div class='image-container'>{{ paragraph.field_image }}</div>
        <div class='text-container'>{{ paragraph.field_text }}</div>
    {% endif %}
{% endfor %}

```
> 1 votes

# Answer
I think you can use DraggableViews for sorting content, and then it will be very easy to output without extra logic.
> 0 votes

---
Tags: theming, paragraphs
---


# Question
Title: How can a controller change the url reported to browser?
I have got two routes - one is for pausing mail jobs, the other one for listing them.

When I click on "pause" - the pause route:

1. does it's thing
2. internally calls the list route *with a couple of extra nontrivial parameters* and fetches it's render array
3. returns render array

However, I'd like the browser to report the url of the list-route instead of the pause-route. How can I achieve this?

# Answer
You've already tagged the question with "redirect", so this is what you need to do in step 2+3. Don't return a render array, but a redirect response to the second route providing a couple of extra parameters:

```
return $this->redirect('second.route', ['route_parameter' => '123'], ['query' => ['foo' => 'bar']]);

```
> 0 votes

---
Tags: 8, routes, uri, redirection
---


# Question
Title: Rewrite results for user picture to except tokens
I have a user role called "Residents" in D7, and created a view the show profile information. I want to add colorbox to the User Picture, but there is only one token available \[picture\]. How do I add the image path as the destination if I can only use one token (see attachment)?

# Answer
Please take a look at these two solutions:

https://www.drupal.org/node/2396813#comment-11571515

and

Getting user photo url and profile url using views\_json
> 0 votes

# Answer
Generally I would advocate using an image field on the user entity over the legacy user picture feature. The latter has a lot of limitations and you have just discovered one of them. If you try solving this issue by in the theme layer you'll find in the template that all you have to work with is an opaque "picture" variable containing the image html plus the original account object, meaning that to do anything different you have to re-implement the logic that generated the image html yourself. Not very helpful.

By using a custom image field you have access to a whole raft of contrib modules that integrate with it - including colorbox - without the need for custom code.
> 0 votes

---
Tags: views, users, tokens, javascript
---


# Question
Title: Is it possible to resize image before saving it with media module?
I am building a site using Drupal 7, in which users can upload content in a form, also images. The images will be uploaded and stored with the Media module version 7.x-2.x-dev.

I want to allow users to upload any image up to 10 MB of size.

But, I don't want to have many pictures as big as 10 MB on my server. I prefer to save the image only after it has been resized to 800x600 to have more space on my server.

How can I achieve this with the Media module?

In addition, what is the difference between the field type "file" to "image" when rendering images with the Media module?

There is an option to chose "Field Type: File" and "Widget Type: Media Browser", and then chose rendered file, and then image on the Media settings (here is a great guide to the Media module). Another option is to chose "Field Type: image" and "Widget Type: Media Browser".

# Answer
> 0 votes
First off, image dimensions are not the same as image sizes. Images could have the dimensions of 800x600 but still exceed 10 MB in size.

One possible solution is to create new image styles under `/admin/config/media/image-styles/` providing your desired dimensions (e.g. 800x600). See attached image:

Then under the `Manager Displays` section of the Content Type containing the image field, choose the Image style you just created. See attached image:

Then set the `Maximum upload size` for your field in the `Manage Fields` section of the Content Type containing the image field. See attached image:

# Answer
> 0 votes
To crop images before saving them, you can use these modules on your drupal website:

1. Manual Crop
2. Imagefield Crop

There are some other modules as well, you can find of a list of image crop modules and comparison among there features from link below:

Image crop modules comparison

# Answer
> 0 votes
To resize on saving, use max-image-size module, from module page:

> Simply enable the module and it will begin resizing images when they are uploaded. It will scan for images above the configured dimensions once a day and queue them to be resized.
>
> This is different from the core image field size restrictions in that it will work on already uploaded files and imported content.

---
Tags: 7, media
---


title: Fetch Customer Profile from Line Items

text:
# Question
Title: Fetch Customer Profile from Line Items
In a webshop I’ve build I want to send individual e-mails to owners of a prodruct in the shop after a product is sold. To do this I got this as a solution: Send mail to product owner with Rules

But with this I’m only able to send the product owner an e-mail about the product. I am not able to add a shipping/billing address or mailadres form the customer profile to it.

When I try to add the customer profile as a parameter to the component the rules breaks and doesn't work anymore.

This is an export of my component:

```
{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail" ],
    "USES VARIABLES" : {
      "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" },
      "commerce_order" : { "label" : "Commerce Order", "type" : "commerce_order" },
      "commerce_customer" : { "label" : "Commerce Customer", "type" : "commerce_customer_profile" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "entity_fetch" : {
          "USING" : { "type" : "commerce_customer_profile", "id" : [ "commerce-order:uid" ] },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched user" } }
        }
      },
      { "drupal_message" : { "message" : "Product Mail = [product-fetched:field-e-mailadres-product]" } },
      { "mimemail" : {
          "key" : "[commerce-order:order-id]",
          "to" : "[product-fetched:field-e-mailadres-product]",
          "subject" : "Product order",
          "body" : "OUTPUT PRODUCT INFORMATION AND USER INFORMATION HERE",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

This is the export of my rule to loop trough the line-items:

```
{ "rules_send_mail_to_product_owner" : {
    "LABEL" : "Send mail to product owner",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Custom" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "commerce_order_presave" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "line_items" : "Commerce Line Items" },
          "DO" : [
            { "component_rules_perform_an_action_on_a_selected_line_item" : { "selected_line_item" : [ "line-items" ] } }
          ]
        }
      }
    ]
  }
}

```

I set the rules action to `order presave` as this is the easiest way testing the rule, in the end it should run on `when payment is first payed in full`.

The rule isn't running because of my fault in the parameter settings the parameter `commerce_customer` is giving problems, I get an error that says: `"Missing configuration for parameter commerce_customer"`.

How can I get to this information in my component?

# Answer
> 0 votes
> The rule isn't running because of my fault in the parameter settings the parameter `commerce_customer` is giving problems, I get an error that says: `"Missing configuration for parameter commerce_customer"`.
>
> How can I get to this information in my component?

It looks like you have a mismatch in the variables of your rules component (which has 3 of them) and the rule which invokes that rules component (which only passes a value for the first variable `selected_line_item`).

Here is what I suggest you try to get the 2 remaining variables for your rules component fixed:

* `commerce_order`: in your rule (which invokes the rules component), add the value of it as your 2nd variable (to actually pass that value to your rules component). For sure you have a token available to actually pass it (= `commerce-order`), since your rule already refers to `commerce-order:commerce-line-items` also (which you would not be able to do if you wouldn't have `commerce-order`).
* `commerce_customer`: just remove (delete) that as your 3rd variable in your rules component. It seems you don't need to "pass" that as a variable, as per the (2nd) `entity_fetch` included in your rules component. Whereas this (2nd) `entity_fetch` will return you that `entity_fetched` (BTW, a terribly bad name IMO, consider changing that to something more meaningful like `fetched_user`, or even better `fetched_customer`).

Whatever you end up using (i.e. `entity_fetched`, `fetched_user`, or `fetched_customer`) that's what you can then use within the body of your eMail (any of the tokens related to it).

---
Tags: 7, commerce, rules, mimemail
---


# Question
Title: How do i configure admin email on a shared host? where is that email going?
Can someone explain where the admin emails go once the site is up and running? how does it integrate with email accounts on a shared hosting environment?

to test i sent an email to admin@mynewwebsite.com and it didn't bounce. but also, on the shared hosting account no such email address exists.

not sure really where it's going at this point?

any help or advice would be appreciated.

# Answer
> 0 votes
Go to Configuration \> Site information (admin/config/system/site-information)

and change the "E-mail address" in Site details.

Greetings.

# Answer
> 0 votes
I am answering this so that there is an answer.

If you own a domain name you can **optionally** have email sent to that domain.

There are a great many options for this. The "Rolls Royce" approach is to buy email hosting from a third party such as Rackspace. The shoestring approach by many hosting providers or Domain name sales operations is to provide a redirection service. There is a lot of ground in the middle.

If the email is not bouncing then you likely have an email account set up. Your provider should provide help for POP3 or IMAP settings for use with a local client such as Thunderbird or Outlook. These are hosting questions. SMTP for outwards email can be problematic, use what works. You are not obliged to keep any service you sign up for, you can receive and send email independently.

Ideally you would have bought a package that includes some email rolled up. Ask if they have a "catchall" service.

A DNS enquiry for your domain name should reveal "MX" records.

Yes, it is possible to to have your Drupal server also be a Mail server, this is also not for beginners and may violate the terms of your hosting provider or your ISP (if this is on your own metal).

But really, the out-of-the-box solution is to use your personal ISP provided email and move on from there when you are ready or have sorted out setting up the new email account. Leave important traffic on this in case of outages. Otherwise these are "hosting issues" not Drupal issues.

---
Tags: emails
---


# Question
Title: How to import a live Drupal site into Acquia Drupal Dev Desktop?
I would like to make some major changes to our live Drupal website. I'd prefer to do it in a safe local development environment on my laptop. What are the steps/process to exporting a live Drupal 7 and importing it into the Acquia Drupal Dev Desktop?

# Answer
First, use the Backup and Migrate module to create a copy of the database. Then download all the Drupal site files to your machine as well.

You can set up a local version by using the import option Acquia Drupal Dev Desktop instead of creating a new site and importing the Drupal files you just downloaded.

Then use the Backup and Migrate module again on the local site to synchronise the database.
> 2 votes

# Answer
1. Back up your Drupal folder on the live server.
2. Access PhpMyadmin, and export the database, put it in a folder.
3. Write down the name of your database and any prefix that may have.
4. Create a Folder on your pc where you plan to use as a Dev environment.
5. Copy the backup folder from your live server to this folder.
6. Launch Acquia Drupal Dev Desktop, click Settings -\> Sites -\> Import
7. Click Browse, select your local folder with the Drupal files from your live server.
8. On Database select "I have a MySQL database dump file for may site".
9. Click to Browse the dump file exported on step 2.
10. Write a Server URL for the Dev environment (on Domain).
11. Click import.
12. Profit.

I wrote this from memory, so if you have any problem just post back.
> 1 votes

# Answer
One method of importing an existing Drupal application to Acquia Cloud is to create a Drupal site archive and then use the Acquia Cloud interface to install the site archive. This method works best for applications that aren’t very large (website archives smaller than 100MB).

To import an existing Drupal application to Acquia Cloud using a site archive file, complete the following steps:

Prepare your application before you export it from your current environment.

Create a Drupal site archive file for import by exporting your existing Drupal application.

You can use the tools provided in your existing application environment (including Acquia Dev Desktop), or you can use the Drush archive-dump command. The archive-dump command is available in Drush 4.5 or later. For more information about importing your application using Drush, see Importing an existing application using Drush.

Import your website into the Development environment of your Acquia Cloud application. Acquia Cloud commits your application code to your Acquia Cloud code repository, installs the database, and uploads your files.

from: https://docs.acquia.com/acquia-cloud/create/import/archive/
> 0 votes

---
Tags: 7, importing-exporting
---


title: Create a Custom Ajax in form alter

text:
# Question
Title: Create a Custom Ajax in form alter
Hi i have a problem to create a custom ajax, i have the following code.

the problem is i cannot make the code working no response nothing working for ajax callback, is simple but i try to put i src but still dont works, any help for make this to work, thanks

```
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AppendCommand;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\Response;

/**
 * Implements hook_form_alter().
 */
function custom_form_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_comandas_edit_form' || $form_id == 'node_comandas_form') {

    $form['#attached']['library'][] = 'custom_form/custom_form.library';

    foreach ($form['field_producto']['widget'] as $key => $value) {
      if (is_numeric($key)) {
        if ($value) {
          $valor_producto = $value['subform']['field_cantidad']['widget'][0]['value']['#default_value'] * $value['subform']['field_precio']['widget'][0]['value']['#default_value'];
          $total += $valor_producto;
        }
      }
    }

    // Wrap textfields in a container. This container will be replaced through
    // AJAX.

    // This form is rebuilt on all requests, so whether or not the request comes
    // from AJAX, we should rebuild everything based on the form state.
    // Checkbox values are expressed as 1 or 0, so we have to be sure to compare
    // type as well as value.

    $form['field_total']['widget'][0]['value']['#default_value'] = $total;
    $form['field_total']['#ajax'] = [
      // #ajax has two required keys: callback and wrapper.
      // 'callback' is a function that will be called when this element
      // changes.
      'callback' => '::custom_form_value_change',
      // 'wrapper' is the HTML id of the page element that will be replaced.
      'wrapper' => 'total-wrapper',
      'event' => 'click',
      'effect' => 'fade',
      'progress' => array(
        'type' => 'throbber',
        'message' => 'cargando',
      ),
    ];
  }
}

function custom_form_value_change($form, FormStateInterface $form_state) {
    $reponse = 'total-wrapper';
    //$response = new AjaxResponse();
    //$valor = 40000;
    //$response->addCommand(new HtmlCommand('total-wrapper', $valor));
    return $response;
  }

```

(EDIT)

try other solutions but still dont working, i make this and works but with new fields, no with the existent of the node, i use paragraphs and also no working,some bug of drupal or use that i need?

```
/**
 * Implements hook_form_alter().
 */
function custom_form_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_comandas_edit_form' || $form_id == 'node_comandas_form') {

    $form['#attached']['library'][] = 'custom_form/custom_form.library';

    foreach ($form['field_producto']['widget'] as $key => $value) {
      if (is_numeric($key)) {
        if ($value) {
          //$valor_producto = $value['subform']['field_cantidad']['widget'][0]['value']['#default_value'] * $value['subform']['field_precio']['widget'][0]['value']['#default_value'];
          //$total += $valor_producto;
        }
      }
    }

    $form['field_total']['widget'][0]['value']['#default_value'] = $total;
    $form['field_total']['#ajax'] = [
      // #ajax has two required keys: callback and wrapper.
      // 'callback' is a function that will be called when this element
      // changes.
      'callback' => 'custom_form_value_change',
      // 'wrapper' is the HTML id of the page element that will be replaced.
      'wrapper' => 'textfields-container',
      'event' => 'click',
      'effect' => 'fade',
    ];

    $form['ask_first_name'] = [
      '#type' => 'checkbox',
      '#title' => 'Ask me my first name',
      '#ajax' => [
        'callback' => 'custom_form_value_change',
        'wrapper' => 'textfields-container',
        'effect' => 'fade',
      ],
    ];

    // Wrap textfields in a container. This container will be replaced through
    // AJAX.
    $form['textfields_container'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'textfields-container'],
    ];
    $form['textfields_container']['textfields'] = [
      '#type' => 'fieldset',
      '#title' => "Generated text fields for first and last name",
      '#description' => t('This is where we put automatically generated textfields'),
    ];

    if ($form_state->getValue('ask_first_name', NULL) === 1) {
      $form['textfields_container']['textfields']['first_name'] = [
        '#type' => 'textfield',
        '#title' => 'First Name',
        '#required' => TRUE,
      ];
    }
    if ($form_state->getValue('field_total')) {
      $form['textfields_container']['textfields']['last_name_2'] = [
        '#type' => 'fieldset',
        '#title' => 'Last Name 2',
        '#description' => t('This is where we put automatically generated textfields'),
      ];
    }

  }
}

function custom_form_value_change($form, FormStateInterface $form_state) {
    $reponse = 'total-wrapper';
    //dpm($form_state);
    //$response = new AjaxResponse();
    //$valor = 40000;
    //$response->addCommand(new HtmlCommand('total-wrapper', $valor));
    return $form['textfields_container'];
}

```

# Answer
> 3 votes
The double colon (::) is used within classes, to indicate the current class. Hooks are not OOP (classes), they are procedural code. So you leave out the double colon:

```
  'callback' => 'custom_form_value_change',

```

Though I'd call it something more descriptive like `[module]_[form_id]_ajax_callback`.

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


# Question
Title: Pre fill multiple paragraphs while adding node
I want to prefill multiple paragraphs when user click on "add node" for specific content type. What would be a good way to do this ?

# Answer
> 5 votes
You can't reuse existing paragraphs, you have to create new paragraphs for each node:

```
$paragraph1 = Paragraph::create([
  'title' => 'Paragraph 1',
  'type' => 'paragraph_type1',
]);
$paragraph1->save();

$paragraph2 = Paragraph::create([
  'title' => 'Paragraph 2',
  'type' => 'paragraph_type2',
]);
$paragraph2->save();

$node = Node::create([
  'title' => 'Node with two paragraphs',
  'type' => 'article',
  'field_paragraph' => [$paragraph1, $paragraph2],
  ]);
$node->save();

```

You could place this code in a custom controller:

```
  public function addCustomContentType() {
    $node = $this->entityTypeManager()->getStorage('node')->create([
      'type' => 'custom_content_type',
    ]);

    // create paragraphs, don't save them yet, in case the node is not submitted

    $paragraph1 = $this->entityTypeManager()->getStorage('paragraph')->create([
      'title' => 'Paragraph 1',
      'type' => 'paragraph_type1',
       // more field data
    ]);

    $paragraph2 = $this->entityTypeManager()->getStorage('paragraph')->create([
      'title' => 'Paragraph 2',
      'type' => 'paragraph_type2',
      // more field data
    ]);

    // prefill the paragraph field in the node with the paragraphs
    $node->field_paragraph = [$paragraph1, $paragraph2];

    $form = $this->entityFormBuilder()->getForm($node);

    return $form;

```

# Answer
> 2 votes
You can hack simple fields during `hook_form_alter()`, but paragraphs have too complicated structure. It must be done earlier, during fresh node creation, before the form is created.

```
function MY_MODULE_node_create(Drupal\Core\Entity\EntityInterface $entity) {

  $bundle = $entity->bundle();
  if ($bundle != 'MY_CONTENT_TYPE') {
    return;
  }

  // you may add here additional checks
  // to make sure node creation happens
  // on node add page

  $pg = Paragraph::create([
    'type' => 'MY_PG_MACHINE_NAME',
    'field_reference' => ['target_id' => 111],
    'field_integer' => 2222,
  ]);

  // Insert here as many paragraphs as you need.
  $entity->field_paragraphs = [$pg];

}

```

See also: hook\_entity\_create()

---
Tags: paragraphs
---


title: Get the value of a custom user field

text:
# Question
Title: Get the value of a custom user field
I have a custom form that needs to display a default value from a custom user field. The field was created under /admin/config/people/accounts/fields and its machine name is field\_r\_period\_length\_sec.

```
//get user
$userCurrent = \Drupal::currentUser();
$uid = $userCurrent->id();
$r_period = $userCurrent->field_r_period_length_sec;

```

However, the value doesn't show and I get this error:

> Notice: Undefined property: Drupal\Core\Session\AccountProxy::$field\_r\_period\_length\_sec

What am I doing wrong?

# Answer
> 28 votes
Berdir's answer gave me a search term that got me this:

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

```

After a bit of trial and error, this is the code that works, in case anyone else needs:

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$r_period = $user->field_r_period_length_sec->value;

```

For multiple values, use

```
$r_period = $user->get('field_r_period_length_sec')->getValue();

```

# Answer
> 3 votes
The current user object is not a user entity. You need to load the user with that ID to access any field except the information specified by `AccountInterface`.

# Answer
> 3 votes
I don't know since when these answers doesn't work anymore, but with Drupal 8.5 the above solution return null all the time.

After investigation the solution to access custom field from a user profile is:

```
$activeProfile = \Drupal::getContainer()
  ->get('entity_type.manager')
  ->getStorage('profile')
  ->loadByUser(User::load([uid]), '[profile_machine_name]');

```

Then you can do

```
$activeProfile->field_xxx->value

```

# Answer
> 1 votes
`Entity::load()` is based off of `\Drupal::entityManager();` which is deprecated.

A better way to do this is by using entityTypeManager().

```
$user = \Drupal::entityTypeManager()->getStorage('user')->load($current_user->id());
$r_period = $user->field_r_period_length_sec->value;

```

---
Tags: users, 8
---


# Question
Title: How can I get the uploaded file path of a contact form in drupal 8
I'm using the `hook_mail_alter()` to create a custom email for contact forms. I was able to get the fields labels and values and use a twig template to send the email. Most of it is working just fine, but my problem is when I use file fields on the contact form. I want to be able to show the path of the uploaded files. When I use the default drupal email, it shows the paths at the end of the file. I want to do the same thing at my custom email. Can anyone tell me how to do this?

# Answer
> 3 votes
You can get the file entity directly from the field and check if the field is not empty before applying any methods on the file object:

```
/** @var \Drupal\contact\Entity\Message $contactMessage */
$contactMessage = $message['params']['contact_message'];
$file = $contactMessage->field_file->entity;
if (!empty($file)) {
  $fileInfo[] = [
    'value' => $file->getFilename(),
    'url' => $file->url(),
  ];
}

```

# Answer
> 1 votes
I solved my question by getting the file from the fileId.

```
/** @var \Drupal\contact\Entity\Message $contactMessage */
$contactMessage = $message['params']['contact_message'];
$fileId = $contactMessage->get('field_file')->getValue()[0]['target_id'];
$file = \Drupal\file\Entity\File::load($fileId);
$fileInfo[] = [
    'value' => $file->getFilename(),
    'url' => $file->url(),
];

```

---
Tags: 8, forms, hooks, files, emails
---


# Question
Title: How do I create a download link knowing the uploaded file ID?
I've a column in database containing the IDs of the files uploaded using a *managed file* form field.

How do I create a link to the uploaded file knowing its file ID?

EDIT : The obvious solution doesn't work for me , i'm using another table where i put my Fids .

this is the warning i got everytime : Notice: Trying to get property of non-object in Affichage\_form() (line 188 of C:\wamp64\www\Gestion\_tickets\_licences\sites\all\modules\Recherche\Recherche.module). \<\< 188 : $uri= $file-\>uri; \>\>

Solution : Thank you for you help . my solution for my problem is , Once I upload the file , I create the url. Instead of saving Fid , I save the url , It worked .For the download link , I used Alen syntax and it worked great .

# Answer
> -1 votes
You can load file with id with file\_load function and then you need to write `<a href='file_path' download > file_name </a>`

# Answer
> 0 votes
First, load the file using file\_load(FILE\_ID) and get URI like below:

```
$file = file_load(1);
$uri = $file->uri;

```

After that generate link using file\_create\_url();

```
$url = file_create_url($uri);

```

Get file name also:

```
$filename  = $file->filename;

```

And finally, create a link using l().

```
l(t($filename), $url);

```

and output will be like `<a href="http://d7.local/sites/default/files/pictures/picture-6.png">picture-6.png</a>`

---
Tags: 7
---


# Question
Title: Why when I do a configuration export does the config.tar.gz in tmp not get copied to the sync folder?
This happens when I use the UI and `drush cex`. The config.tar.gz is created in the tmp folder but nothing is created in the sync folder that I created in sites/default.

I have searched for similar tickets here, on Drupal.org and searching in google! I find references to folder and file permissions (I have tried 777 on most) and references to a `.htaccess` file in the sites/default folder with specific content.

The content my .htaccess file in sites/default is:

```
# Deny all requests from Apache 2.4+.
<IfModule mod_authz_core.c>
  Require all denied
</IfModule>

# Deny all requests from Apache 2.0-2.2.
<IfModule !mod_authz_core.c>
  Deny from all
</IfModule>
# Turn off all options we don't need.
Options -Indexes -ExecCGI -Includes -MultiViews

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
    # Override the handler again if we're run later in the evaluation list.
    SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

I am using the DDEV environment to create docker containers on my local Ubuntu 10.04 VM (VirtualBox) on my Windows 10 PC. I use the DDEV default settings.php for Drupal 8. I then added the following lines:

```
// Config sync directory.
#$config_directories['sync']='sites/default';
$config_directories = array (
    CONFIG_SYNC_DIRECTORY => 'sites/default',
);

// Configure private file path
$settings['file_private_path']='sites/default/private';

// Configure trusted host patters to prevent HTTP HOST header attacks
$settings['trusted_host_patterns'] = [
    '^<projectname>\.ddev\.local$',
];

```

I have tried variations of the `$config_directories` definition including the commented out version. I also defined the sync directory to be `'sites/default/sync'`. I have created the 'sites/default/sync' directory. I have tried deleting the config.tar.gz in the tmp directory which gives the log message 'The file tmp/config.tar.gz was not deleted because it does not exist.' and then creates the config.tar.gz file in the tmp directory.

I have tried `find . -name *.tar.gz` to search all the directories for any such files in case it has put it somewhere unexpected and no luck!

OK so for my versions:

Ubuntu 18.04, DDEV 0.18.0 (Nginx 1.14.0, PHP 7.1.16-1+0~20180405085551.16+jessie~1.gbp4937aa, Database 5.5.5-10.1.28-MariaDB ), Drupal 8.5.5. I have done these tests on a standard Drupal installation with the only additional module being Backup and Migrate 8.x-4.0. I have enabled a few of the core modules not enabled by the standard installation (e.g. Media).

There don't appear to be any messages in my latest Drupal error log for today (my most recent test of this bug).

Is there anything else I can supply that might help diagnose what I am doing wrong?

# Answer
The best way to store configuration is to store it outside of Drupal root directory.

For example you will have next project structure:

Where:

1. **config/sync** is a directory with your sync configuration.
2. **public\_html** is a directory with your Drupal 8.

In your **setting.php** just add this

```
$config_directories['sync'] = '../config/sync';

```

And export your active configuration using drush

```
drush cex

```

That's all. In **config/sync** directory you will a files list of all your configuration.
> 1 votes

---
Tags: 8, configuration
---