# Question
Title: Impossible to update some modules via Composer
I've updated a D8 website from 8.7 to 8.8.1 with SSH and composer. **For some modules** (in SSH 3rd column is marked in yellow) it is **not possible to update** them. I understand that when they are marked in yellow some dependencies are missing?

The rest of the modules are updated successfully.

Below the **list of modules that needs an update** (3rd column is marked in yellow):

```
drupal/blazy         1.0.0-rc5 2.0.0-rc6 Provides basic bLazy integration for lazy loading and multi-serving images.
drupal/file_mdm      1.1.0     2.0.0     Provides a service to manage file metadata.
drupal/file_mdm_exif 1.1.0     2.0.0     Provides a file metadata plugin for EXIF image information.
drupal/file_mdm_font 1.1.0     2.0.0     Provides a file metadata plugin for TTF/OTF/WOFF font information.
drupal/slick         1.2.0     2.0.0     Slick carousel, the last carousel you'll ever need.
drupal/slick_views   1.0.0     2.1.0     Provides Slick carousel integration with Views.

```

In **composer.json**: **slick and slick\_views are added**. Other above modules are not located in the composer.json:

```
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "php": ">=5.6",
        ...,
        "drupal/field_group": "^1.0",
        "drupal/slick": "^1.1",
        "drupal/slick_views": "^1.0"
        ...,
    },
    "require-dev": {
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": ["load.environment.php"]
    },
    "scripts": {
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "enable-patching": true,
        "composer-exit-on-patch-failure": true,
        "patchLevel": {
            "drupal/core": "-p2"
        },
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/Commands/{$name}": ["type:drupal-drush"]
        },
        "drupal-scaffold": {
            "initial": {
                ".editorconfig": "../.editorconfig",
                ".gitattributes": "../.gitattributes"
            }
        },
        "patches": {}
    }
}

```

**With these commands: nothing to install or update**

```
composer update drupal/slick --with-dependencies
composer update drupal/slick

```

In the backoffice D8 (/admin/modules/update) it reports that field\_group needs an major update. That is not reported via SSH:

```
composer outdated "drupal/*"

```

I've tried to remove "field\_group" to reinstall it:

```
composer remove drupal/field_group
...
composer require drupal/field_group
...
Using version ^1.0 for drupal/field_group

```

**Why is it not using version: 8.x-3.0-rc2?**

I've removed the vendor folder. I've removed the composer.lock file.

What can I do to update the site to have the latest versions applied for the above list of modules? Simply removing and reinstalling is not working.

# Answer
> 0 votes
Major version changes contain breaking/incompatible changes in SemVer / Semantic versioning. If you would update them, it would break modules that depend on the old version. Therefore most projects lock composer entries to one specific major version number. Also doing a default `composer require vendor/project` \- without denoting an explicit version number - will create an entry locked to the current major version number.

The common way for a major version change is to explicitly `composer require` a new major version, but this usually means manually doing extra upgrade/migration steps outside of composer.

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


# Question
Title: Why isn't the value for a new Boolean field rendered?
I added a new Boolean field to a content type. For some nodes, I did set this field.

>

Still, the field value is not shown on the node page.

>

Why?

I realize that, as long no value is set for the new field, it isn't present in the database, but (as seen in the screenshots) on that node, the field is set to *true* and it should be shown on the node page, shouldn't it?

# Answer
This is a Durpal 7 Problem. It lies about that it will fall back to 0/1 if you don't provide your custom true/false values, when it actually does not fall back. See https://www.drupal.org/project/drupal/issues/1750950

In short, in the field-settings, you have to set on-/off- values. If you don't the default renderer will output an empty string and in the edit forms the field's checkbox or radio-buttons will have no label.
> 1 votes

---
Tags: nodes
---


# Question
Title: Create a button with an icon in render array, that can be themed by arbitrary contributed themes
Drupal 8 does not use HTML button tag for creating buttons, it instead uses the input tag to create buttons. This works fine for most part, except for buttons which include an icon gets messed up by themes which replace the icons with a gradient. For example, Bootstrap theme will replace the button icon with gradient, that makes the button empty.

Is there a way to create a button via render array that will generate \<button ...\>\<img ... style button?

Alternatively, is there a way for a module to only use a twig template in special case, but not all the time.

Other ideas?

Update: May 7 2020.

---

I have filed a Drupal Core issue to support new render type for imagebutton, hopefully it will get some attention, as this can't really be solved in contrib space.

# Answer
You can create a custom HTML tag using the following code.

```
return [
  '#type' => 'html_tag',
  '#tag' => 'button',
  '#value' => 'whatever value...',
];

```

Another solution is custom theme function that creates the button. In this case, the theme function can be used by code similar to the following one.

```
return [
  '#theme' => 'your_template',
];

```

You can read more about rendering custom templates on Create custom twig templates for custom module.
> 2 votes

---
Tags: 8, theming
---


title: Aegir hosting_https commercial SSL cert

text:
# Question
Title: Aegir hosting_https commercial SSL cert
Similar to Aegir no longer seems to be adding SSL info to apache config files for sites

The documentation still mentions a way to use commercial certs: https://docs.aegirproject.org/usage/advanced/ssl/#commercial-certificates

I too have run into the problem aegir\_https not working the same way regarding chain certs.

Running aegir3-provision/stable,stable,now 3.182

LE is not an option for our org unfortunately.

Is there a way to use commercial apache certs with aegir\_https/hosting\_https?

# Answer
As stated at the top of that documentation page, everything there is legacy and is no longer supported.

The feature request for being able to use commercial certificates with Aegir HTTPS (the officially supported way of running HTTPS now), is Add a 'manual' Certificate implementation.

So your options are either:

* Write a patch yourself (and upload it to the issue), or
* Pay us, the maintainers, (or someone else) to do it for you.
> 0 votes

---
Tags: aegir
---


# Question
Title: Set permanent status for managed_file in theme settings
I'm creating some Drupal 8 theme and I need some additional settings for it. So, I have to add some managed\_file field in theme settings.

I have theme-settings.php file where I define this field and I want to make this file permanent.

There is what I have in theme-settings.php so far:

```
<?php

/**
 * @file
 * Provides an additional config form for theme settings.
 */

use Drupal\Core\Form\FormStateInterface;

// Set theme name to use in the key values.
$theme_name = \Drupal::theme()->getActiveTheme()->getName();

/**
 * Implements hook_form_system_theme_settings_alter().
 *
 * Form override for theme settings.
 */
function onion_form_system_theme_settings_alter(array &$form, FormStateInterface $form_state) {
  $form['options_settings'] = [
    '#type' => 'fieldset',
    '#title' => t('Theme Specific Settings'),
  ];

  // Main navigation logo
  $form['options_settings']['menu_logo'] = [
    '#title' => t('Menu Logo'),
    '#type' => 'managed_file',
    '#default_value' => theme_get_setting('menu_logo'),
    '#upload_location' => 'public://',
    '#description' => t('Logo below main navigation. Available extensions (.gif .png .jpg .jpeg)'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg')
    ),
  ];

  $form['#submit'][] = '_onion_form_system_theme_settings_submit';
}

function _onion_form_system_theme_settings_submit(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {
  $menu_logo_id = $form_state['values']['options_settings']['menu_logo'];
  $menu_logo_file = \Drupal\file\Entity\File::load($menu_logo_id);

  // set status to permanent so that its not deleted
  $menu_logo_file->setPermanent();
  $menu_logo_file->save();
}

```

But I'm getting this warning:

```
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function '_onion_form_system_theme_settings_submit' not found or invalid function name in Drupal\Core\Form\FormSubmitter->executeSubmitHandlers() (line 111 of core/lib/Drupal/Core/Form/FormSubmitter.php).

```

What I'm doing wrong there and what is the best and right way to set file permanent?

# Answer
> 3 votes
I think you just need to adjust your submission handler; don't include the fieldset "options\_settings". I use the `getValue()` method and pass it an array of values, the form key and the index of its value.

```
  if ($file_id = $form_state->getValue(['header_background', '0'])) {
    $file = \Drupal::entityTypeManager()->getStorage('file')->load($file_id);
    $file->setPermanent();
    $file->save();
  }

```

---
Tags: 8, forms, files
---


# Question
Title: In the Features module, what does "Recreate" do?
What does it mean to "recreate" a feature? How does this affect the database? How does it affect the files, if at all?

# Answer
> 2 votes
Recreate allows you to re download the feature, including any changes made to config along with the option to add new config.

---
Tags: 7, features
---


# Question
Title: How to write SoapClient request which has basic auth in it?
Actually I need to implement SoapClient in Drupal 8. Following XML is Request:

```
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="http://www.example.com/common/ServiceRequestHeader_v1_0/types" xmlns:typ1="http://www.example.com/customer/CustomerViewRequest_v1_0/types">
   <soapenv:Header>
      <typ:serviceRequestHeader>
         <applicationCredential>
            <ID>USERNAME</ID>
            <credential>*****</credential>
         </applicationCredential>
         <transactionModel>
            <synchronousRequest>true</synchronousRequest>
         </transactionModel>
         <userCredential>
            <ID>RITESH</ID>
         </userCredential>
      </typ:serviceRequestHeader>
   </soapenv:Header>
   <soapenv:Body>
      <typ1:serviceRequest>
         <requestPreamble>
            <companyCode>IN</companyCode>
            <customerNumber>12345678</customerNumber>
         </requestPreamble>
      </typ1:serviceRequest>
   </soapenv:Body>
</soapenv:Envelope>

```

I have tried following code for the same but it is failing and I am not able to make any progress on this:

```
    $client = new SoapClient('https://example.com:9043/CustomerView_v1_0_vs0',
    array(
        // Stuff for development.
        'trace' => 1,
        'exceptions' => true,
        'cache_wsdl' => WSDL_CACHE_NONE,
        'features' => SOAP_SINGLE_ELEMENT_ARRAYS,

        // Auth credentials for the SOAP request.
        'ID' => 'USERNAME',
        'credential' => 'Password',

    )
);
    dump($client); die;

```

Its giving below error:

```
SOAP-ERROR: Parsing WSDL: Couldn't load

```

Can anyone suggest some way on this ?

# Answer
I believe the answer is nearly there for you, but ID and credential are the wrong keys in the options array.

```
       'login' => 'USERNAME',
       'password' => 'Password',

```

I suggest that you put the username and password into conf in your settings.php file so they are not in your codebase nor your site configuration data. See How secure are variable\_get and variable\_set? for details on how to securely have credentials in Drupal's config system.
> 0 votes

---
Tags: 8
---


# Question
Title: Don't repeat yourself: Natural place for clculations on the FieldItemList of a custom FieldType wanted
I have a custom field type that contains a number field, among others.

```
class MyFieldItem extends FieldItemBase {
    public static function propertyDefinitions($field_definition) {
        $properties = [];
        $properties['some_number'] = DataReferenceTargetDefinition::create(
            'integer'
        );
        ...
    }
    ...
}

```

I need the sum of all values of the property `some_number`. A function adding the numbers would look like this:

```
function addAllNumbers($items) {
    $sum = 0;
    foreach ($items as $item) {
        $sum += $item->get('some_number')->getValue();
    }
    return $sum;
}

```

I need this sum for many purposes, like to display it in the formatter, or to validate forms.

Now, I've found that I'm calculating this sum in several places in my code. But an important programming principle tells me: "Don't repeat yourself!"

**Where is a natural place to perform calculations on the FieldItemList of a custom FieldType?**

I see several candidates for such a place.

* The `.module` file. However, this is hardly connected to the custom FieldType and often a confusing collection of random things.
* The `MyFieldItem` class defining the custom FieldType. Here, the iteration would go over `$this->parents`. However, I don't see a way to access the FieldType object from within the Formatter.
* The formatter. However, then it would be necessary to somehow format the FieldItemList during the form validation.
* Some utility class. But probably, other developers would find that strange in the future.

> There should be one-- and preferably only one --obvious way to do it.
> (The Zen of Python, by Tim Peters)

# Answer
> 3 votes
The natural place would be a method in a custom field item list:

```
class MyFieldItemList extends FieldItemList {

  public function addAllNumbers() {
    $sum = 0;
    foreach ($this->list as $item) {
      $sum += $item->some_number;
    }
    return $sum;
  }

}

```

Set the list class in the field type:

```
 * @FieldType(
 *   ...
 *   list_class = "\Drupal\mymodule\MyFieldItemList",

```

---
Tags: entities
---


title: Cannot log in as Drupal admin

text:
# Question
Title: Cannot log in as Drupal admin
I have installed phpMyAdmin.

I can see the admin user (uid=1) in each of the two databases

I have reset the password using;

**update users\_field\_data set pass=Password("new\_password");**

I can see that the pass hash has changed confirming a changed password.

I got to http://mysiteURL/user/login and enter the admin name (shown in users\_field\_data table) and the new password.

Upon submit I only get the border of the login name field changed to red.

I have cleared the sessions table and removed the cache\_entity data for uid=1 with no change in behaviour.

**yum list | grep -i php**

returns a lot of php packages from version 5.6 to 7.3. I am not sure if this is normal but php seems to work since both websites load and I can use phpMyAdmin and phpinfo() returns php7.2.7

I have checked error logs for each website, nginx, drupal and php with no obvious errors.

Curiously drush cli does not work i.e.

**./drush uli**

**sh: module: line 1: syntax error: unexpected end of file sh: error importing function definition for \`BASH\_FUNC\_module' Drupal\Core\Database\ConnectionNotDefinedException: The specified database \[error\] connection is not defined: default in /app/jbi2/core/lib/Drupal/Core/Database/Database.php:361**

I have now resorted to reviewing the Drupal 7 installation steps.

Thanks in advance for any well informed replies.

# Answer
> 2 votes
Drupal 7 and 8 do not use a straight md5 password hash. The hash includes a site specific "salt" string that is created with you set up the site. This is in the settings.php file generally.

To use SQL to set a password, you will need to use the password-hash.sh file which is located in the core/scripts directory.

Run this from your web root directory like ./core/scripts/password-hash.sh\` newpassword

Use the string created as the value for your password in query with no Password function.

Re:Drush

You might try running it in the same directory as your site's settings.php file. With D8, some versions of drush have a hard time finding this unless you run it there or set up an alias for the site.

Older version could find it settings.php based on your location (e.g. in a subdirectory of the site directory or would use the sites/default). But newer Drush versions need more information.

# Answer
> 0 votes
There are some good answers here about why the steps you've used are not working and what you can do to resolve them.

I have another idea about how to get logged in as uid 1:

1. Get a session on the site, since you mention clearing the sessions table I guess you know what is triggering the generation of a session on your site.
2. Open a mysql prompt, e.g. in phpMyAdmin
3. Find the session that corresponds to your browser, you can look at the cookies in your browser and find the sessid that matches the value in the sessions table.
4. Update the uid for that session to be uid 1
5. Refresh the browser and you should now be uid 1

---
Tags: authentication-authorization
---


# Question
Title: "Fields pending deletion" stopping module unistall - how to delete manually?
I'm getting a "Fields pending deletion" error when trying to uninstall the Dynamic Entity Reference module. I also cannot disable the module as the tick is greyed out (unless I'm missing how to disable modules in Drupal 8).

I've run cron and cleared the caches many, many times and have checked /admin/reports/fields but there is no mention there of any fields using this module.

I have found suggestions for Drupal 7 saying to delete the fields from the `field_config` database table but this table does not exist in Drupal 8. Is there any way to get rid of these zombie fields? They must be stored somewhere!

Please don't tell me to use Drush, I wish I could, believe you me, but I don't have shell access, just sftp and phpmyadmin.

# Answer
It turns out that deleted fields in Drupal 8 are stored in the `key_value` table.

To find them:

```
select * from key_value where name = "field.field.deleted" or name = "field.storage.deleted"

```

The values are stored as a blob, but can be viewed (e.g. in phpmyadmin you can click on it to download, and view in vim or similar). The value does not make much sense to a human, but having gone through the code printing and error-logging various things it was clear to me that these entries were what was holding up the uninstall. I backed up the table and deleted the entries, and then was able to uninstall the module.

The same suggestion is made here in answer to a related issue:

https://drupal.stackexchange.com/a/230199/25792
> 14 votes

# Answer
I encountered the same issue with a field which was used in 7000+ entities, while the purge\_batch\_size: 1000 is not work, increase the number to over 7000 works.

So

purge\_batch\_size: 10000

works for my instance.

I solved this problem just by execute the following command:

```
drush php-eval 'field_purge_batch(10000);'

```

based on

https://drupal.stackexchange.com/a/261669/90460

then run

drush cron

then I can uninstall the module which was prevented.
> 19 votes

# Answer
The fields are deleted by cron runs. But only a fixed batch size. You can configure a higher value. If you can't use drush you can do this in UI. Go to the page */admin/config/development/configuration/single/import* and add in `field.settings` a higher batch size:

```
purge_batch_size: 1000

```

and run cron again.
> 4 votes

# Answer
I ended up having to empty the field\_collection\_item table in order to uninstall field\_collection module on my system. In case anyone else is still having problems after trying the other suggestions here.
> 0 votes

---
Tags: 8, entities, database
---


# Question
Title: Display fields from a paragraph as a single field
I have a paragraph which is essentially a date range, however, the individual dates can have prefixes, suffixes, can be in differing formats, I have a dropdown to select the format and dates need to be displayed differently depending on whether they span within a decade, over decades or over century boundaries. The date values have been split out into a daterange field so we can search / filter by date, however, within the parent paragraph, I'm wanting to return just the processed date instead of the list of fields.

I can do the IF this RETURN xyz to get the date fields into the required formatted string, however, I'm struggling to find how I can build this into a plugin and attach to my desired paragraph(s) / nodes.

It's fairly simple to do this within the theme templates, however, I'm needing to do this at a field / node level, not a twig template as the data will be pulled both as a traditional web page, but will also need to be pulled out via XML export, probably within various views and so on, so don't want to be doing the presentation transformation in multiple places. I need it to be independent of the site theme files.

This is in Drupal 8.8

Hope this makes sense.

# Answer
If you wish to have absolute control on the display of your date range, I'd recommend you to create a module with a new FieldFormatter to expand one of the DateRange fieldformatters (the original files are in code/modules/datetime\_range/src/Plugin/Field/FieldFormatter).

By overriding the viewElements() function, you'll be able to set the desired display(s) for your date range from one place and independent from the site theme files.

Once your new fieldformatter file is created, go to your paragraph "manage display" page and modify the display of your date range field to your new fieldformatter.

Hope this helps.
> 2 votes

---
Tags: 8
---


# Question
Title: Programmatically update field collection data in custom entity
I am in desperate need of help.

I have a custom entity called **Question** which has a bundle called **data**. Within the data bundle, I have a collection field called **options** with two subfields called **correct\_option** & **misc\_option**.

```
-Question
 -Data
  -options
   -correct_options
   -misc_options

```

**I am desperately trying to programmatically write data into those 2 option fields** but the following code is not working:

```
$field_collection_item_value = 1596; // Get field collection item value.

$field_collection_item = entity_load('field_collection_item', array($field_collection_item_value)); // Load that field collection item.

$field_collection_item->save(); // Save field-collection item.

```

The *1569* is the ID of an existing question entity.

Whenever the code is executed I get the following error:

> Fatal error: Call to a member function save() on array

I would appreciate any help. I'm at a loss and not sure how to get this working.

# Answer
> 0 votes
Please use below code for update existing field collection data

```
//$item_id load item id from your node
//enter_update_field_mechine_name replace with your field name
  $field_collection_value = field_collection_item_load($item_id);
  $field_collection_value->enter_update_field_mechine_name['und'][0]['value'] = 'update text here';
  $field_collection_value->save();

```

This code worked for me Thank you

---
Tags: 7, entities
---


# Question
Title: How to use views filter criteria in a custom exposed view filter?
I am using Drupal 8.7.11 and have created a custom views exposed filter which provides users the option to filter an entity reference field using a checkbox list of names instead of autocomplete.

At the moment I have hardcoded the query conditions to build the list in a entity query with certain content checks e.g. date is in the future

However I would like to reuse the filter in a different view which doesn't need to check if a date is in the future.

Is it possible to either get the node ids from the view result, which I can then build the option list from or get the existing views filter criteria that the view uses to put into my list query?

Here is the code I have so far which works for on specific view.

**views\_mods.module**

```
function views_mods_views_data_alter(&$data) {
  $data['node__field_event_tutor']['tutor'] = array(
    'title' => t('Tutor'),
    'filter' => [
      'title' => t('Tutor'),
      'help' => t('Select by tutor - provided by views mods module.'),
      'field' => 'field_event_tutor_target_id',
      'id' => 'views_mods_tutor',
      'group' => 'Content'
    ],
  );
}

```

**src/Plugin/views/filter/TutorViewsFilter.php**

```
<?php
namespace Drupal\views_mods\Plugin\views\filter;

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\user\Entity\User;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\ManyToOne;
use Drupal\views\ViewExecutable;

/**
 * Filters by tutor.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("views_mods_tutor")
 */
class TutorViewsFilter extends ManyToOne {
  /**
  * {@inheritdoc}
  */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->valueTitle = t('Tutor');
    $this->definition['options callback'] = [$this, 'generateOptions'];
  }

  /**
  * Override the query so that no filtering takes place if the user doesn't
  * select any options.
  */
  public function query() {
    if (!empty($this->value)) {
      parent::query();
    }
  }

  /**
  * Skip validation if no options have been chosen so we can use it as a
  * non-filter.
  */
  public function validate() {
    if (!empty($this->value)) {
      parent::validate();
    }
  }

  /**
  * Helper function that generates the options.
  * @return array
  */
  public function generateOptions() {
    $tutor_options = [];

    $time = new DrupalDateTime('now');
    // use entity query to get nids - this respects group memberships
    // so won't show tutors that are attached to nodes the user does not have
    // access to.
    $eq = \Drupal::entityQuery('node');
    $or_type = $eq->orConditionGroup()
      ->condition('type', 'tutorial')
      ->condition('title', 'workshop');
    $or_exclude = $eq->orConditionGroup()
      ->condition('field_exclude_from_listings', 0)
      ->notExists('field_exclude_from_listings'); // IS NULL
    $or_eas = $eq->orConditionGroup()
      ->condition('field_legacy_eas', 0)
      ->notExists('field_legacy_eas'); // IS NULL
    $nids = $eq
      ->condition('status', 1)
      ->condition($or_type)
      ->condition($or_exclude)
      ->condition($or_eas)
      ->condition('field_event_time', $time->format('Y-m-d\TH:i:s'), '>=')
      ->execute();

    $dq = \Drupal::database()->select('node__field_event_tutor', 'fe_tutor');
    $dq->addField('fe_tutor', 'field_event_tutor_target_id', 'uid');
    $dq->addField('f_name', 'field_prof_first_name_value', 'fname');
    $dq->addField('l_name', 'field_prof_last_name_value', 'lname');
    $dq->leftJoin('profile', 'profile', "fe_tutor.field_event_tutor_target_id = profile.uid AND profile.type = 'employee'");
    $dq->leftJoin('profile__field_prof_first_name', 'f_name', 'profile.profile_id = f_name.entity_id');
    $dq->leftJoin('profile__field_prof_last_name', 'l_name', 'profile.profile_id = l_name.entity_id');
    $dq->condition('fe_tutor.entity_id', $nids, 'IN');
    $dq->groupBy('fe_tutor.field_event_tutor_target_id');
    $dq->groupBy('f_name.field_prof_first_name_value');
    $dq->groupBy('l_name.field_prof_last_name_value');
    $tutor_list = $dq->execute()->fetchAll();

    if ($tutor_list) {
      foreach ($tutor_list as $index => $user) {
        $name = trim($user->fname) . ' ' . trim($user->lname);
        if (empty($user->lname)) {
          $account = User::load($user->uid);
          $name = $account->getAccountName();
        }
        $tutor_options[$user->uid] = $name;
      }
    }

    return $tutor_options;
  }
}

```

# Answer
> 2 votes
Based on the following article, I have a suggestion: https://zanzarra.com/blog/custom-views-filter-plugin-drupal-8-bounding-box-geofield . I haven't tried this out myself, but I think the following should work:

* Override the valueForm and valueSubmit methods in your filter class:
    + Create a form that allows you to configure whether or not to include entities in the past (and whatever extra settings you wish to provide)
    + Roll all your values together in an encoded string of some sort: json, serialized array, whatever
* Get your encoded string in the query override out of the value property, decode it, and use yuor settings as parameters for your generateOptions method

Obviously the valueForm is the form that allows yu to configure a filter when you add it to a view.

# Answer
> 0 votes
I started working on a way to achieve this, however I am sure this is not the best way to do this, but it is working for my purposes.

In **src/Plugin/views/filter/TutorViewsFilter.php** I have replaced the hardcoded entity query conditions and created some semi logic to generate them from the views handlers.

```
    $eq = \Drupal::entityQuery('node');

    $filters = $this->view->getHandlers('filter');

    foreach ($filters as $field => $field_data) {
      $condition = [];
      if ($field_data['exposed'] == TRUE) {
//        @TODO: Add option to filter results by user input
        continue;
      } else {
        if ($field_data['table'] == 'node_field_data') {
          $condition = [$field_data["field"], $field_data["value"], $field_data['operator']];
        } elseif($field_data["plugin_id"] == 'datetime') {
          if ($field_data["value"]["value"] == 'now') {
            $time = new DrupalDateTime('now');
            $time_value = $time->format('Y-m-d\TH:i:s');
          } else {
            $time_value = $field_data["value"]["value"];
          }
          $condition = [substr($field_data["field"], 0, -6), $time_value, $field_data['operator']];
        } elseif ($field_data["plugin_id"] == 'numeric') {
          $condition = [substr($field_data["field"],0, -10), $field_data['value']['value'], $field_data['operator']];
        } else {
          $condition = [substr($field_data['table'], 6), $field_data['value'], $field_data['operator']];
        }

        switch ($field_data['operator']) {
          case 'not empty':
            $eq->exists($condition[0], $condition[1], $condition[2]); // IS NOT NULL
            break;
          default:
            $eq->condition($condition[0], $condition[1], $condition[2]);
        }
      }
    }
    $nids = $eq->execute();

```

---
Tags: views, 8
---


# Question
Title: entity_metadata_wrapper Changes not being saved to user Profile2 profile
**Challenge:**

* I have a profile2 taxonomy term reference field (single select) on user profiles called "**field\_member\_interest\_group**".
* On save/update of the user profile, I wan to A) See if the user has a role of "**Elephant**", then if so, select the term of "**Elephant Group**" from that user's taxonomy term reference field and save the changes.
* "MYMODULE" is the name of my module in lowercase.

**My (not working) Code:**

```
function MYMODULE_user_update(&$edit, $account, $category) {
    $account = user_load($account->uid);
    $profile_profile = profile2_load_by_user($account->uid, 'profile');
    $profile_wrapper = entity_metadata_wrapper('profile2', $profile_profile->pid);

    if (in_array('Elephant', $account->roles)) {
        $termX = 3942; //tid of "Elephant Group"
    }
    $profile_wrapper->field_member_interest_group->set($termX);

    //Save changes to the profile entity
    $profile_wrapper->save();
}

```

**Problem:**

The changes are not saved to the user account, they are ignored completely.

*Any thought on what could be going wrong?*

# Answer
> 0 votes
I believe `entity_metadata_wrapper` expects the second parameter to be an object. As in:

```
$profile_wrapper = entity_metadata_wrapper('profile2', $profile_profile);

```

# Answer
> 0 votes
A couple of things:

1. Minor point: In you code `$profile_wrapper = entity_metadata_wrapper('profile2', $profile_profile->pid);`, since you already have the profile object loaded, you can pass the object itself in rather than the pid.
2. You say the problem is that changes are not being saved to the user account. Do you mean they are not being saved to the *user profile entity*? In your code you are using `$profile_wrapper->save();` to save the profile entity, but you haven't changed anything on the user account or written any code to save it.
3. You can try this way of setting the tid: `$profile_wrapper->field_member_interest_group = $termX;` Other than that, the code looks good.

By the way, Daniel's answer is incorrect. You can use entity\_metadata\_wrapper with either an entity ID or with an entity object. See: http://www.mediacurrent.com/blog/entity-metadata-wrapper

# Answer
> 0 votes
In Drupal 7 you can easily go with:

```
global $user;
$new_value = "somevalue";
module_load_include('inc', 'profile2', 'profile2.admin');
$profile2 = profile2_by_uid_load($user->uid, "main");
$profile2__wrapper = entity_metadata_wrapper('profile2', $profile2);
$profile2__wrapper->field_ultimo_display->set($new_value);
$profile2__wrapper->save();

```

---
Tags: entities, users, taxonomy-terms
---


# Question
Title: Programmatically executing a node search
Is it possible to programmatically execute a node search? Maybe via NodeSearch or Drupal\search?

The closest I could get was to programmatically do stuff such as:

```
\Drupal::service('search.index')->clear();

echo \Drupal::service('plugin.manager.search')->getCacheMaxAge();

```

Note that I don't want to use `search_api` but simply what Drupal 8 provides out of the box as a response to `/search/node?keys=test`. Also note that I don't wish to integrate via HTTP.

# Answer
You can achieve that with the search plugin used by the search page entity with the **node\_search** id.

```
use Drupal\search\Entity\SearchPage;

// Default is the node_search page.
$id = \Drupal::service('search.search_page_repository')->getDefaultSearchPage();
$defaultSearchPage = SearchPage::load($id);
$searchPlugin = $defaultSearchPage->getPlugin();
$searchPlugin->setSearch($keywords, $parameters, $arguments);
$searchPlugin->buildResults(); // $searchPlugin->execute() works too if you want raw results

```
> 7 votes

---
Tags: 8, search
---


# Question
Title: Change default format for date field on user register form
I'm new to Drupal 8. In the user registration form, i've added a Date field via manage fields in user account settings. However, I need to customize this field and change its format. I tried 'manage display' but it's not taking effect. Is there something I'm missing. (Ideally, it should look and behave just like field datetime in Drupal 8 webform)

Appreciate any help given.

Thanks

# Answer
> 0 votes
You can implement **template\_preprocess\_field()** and alter the markup of the date field.

```
function MY_THEME_preprocess_field(&$vars) {
  if ($vars['field_name'] === 'field_custom_date_field') {
    $date_format = 'short'; // You need to provide the machine name of the format you want.
    $timestamp = strtotime($vars['element']['#items']->value);
    $markup = \Drupal::service('date.formatter')->format($timestamp, $date_format);
    $vars['items'][0]['content']['#text'] = $markup;
  }
}

```

---
Tags: 8, users, datetime
---


# Question
Title: Changing the text displayed in an Entity Reference Autocomplete
I have an entity reference autocomplete which is populated using an Entity Reference View.

I would like users to be able to type in this autocomplete and for the suggestions to look like this:

"\[title of node\] \[value of custom field\]"

However, it seems like there is no way to achieve this. If I add extra fields into the Entity Reference View, these do not display. If I override the output of the title field in the view, this is ignored. It seems like the Entity Reference Autocomplete simply uses the entity title and ignores the 'Fields' section of the view.

Does anyone have any experience with this? I'm sure it was possible in D7!

# Answer
> 4 votes
You need to implement your own selection plugin for this.

I thought I've already answered a similar question but can't find it anymore.

Assuming the target is a node, extend from `\Drupal\node\Plugin\EntityReferenceSelection\NodeSelection`, otherwise from its parent or appropriate other child class and override `\Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection::getReferenceableEntities()`.

Make that available under its own plugin id (not default:something, just something) and select it in the entity reference field settings.

# Answer
> 0 votes
To add to Berdir's answer. If you are working with a custom entity. Its best to redefine the label method on the custom entity declaration for the autocomplete to work. Simply creating a EntityReferenceSelection plugin will not work with autocomplete since the autocomplete classes reference the label of an entity and there is no clear workaround that I know of?

---
Tags: views, 8, entities, ajax
---


# Question
Title: How can you automatically add CSS classes to <p> tags in the post body?
I'm trying to build a new Drupal site using the Tailwind CSS framework, which relies on inlining CSS classes onto HTML tags.

This is fine in Twig template files where I have direct control of the output and can add the required classes directly, however I'd like to automatically add classes to `<p>` tags (and probably some other, but `<p>` is a good start) within the body of certain post types.

Any idea where I should be looking?

I'm not entirely clear on what the correct terminology to search is, and Google returns plenty of results that are at least a decade old and not relevant for Drupal 8.

# Answer
I have found how to resolve this specifically if using the Tailwind framework, which I am.

You can use the @apply function of the framework to add classes based on common Drupal class names, or ones you specify in your custom html.twig files.

Documentation here: https://tailwindcss.com/docs/functions-and-directives/#apply I am using the Tailwind Starter theme which also uses this function https://www.drupal.org/project/tailwindcss

For example, to apply the `text-xl` utility class to node paragraph tags, I can use the following code in my stylesheet

```
.node-content p {
  @apply text-xl
}

```
> 2 votes

---
Tags: 8, theming
---


title: How $form_state->setRebuild(); works?

text:
# Question
Title: How $form_state->setRebuild(); works?
I have created one form. In function buildForm() I'm firing query by getting parameters from url.

So suppose my url is \[example.com/myform/myshort-title\]\[1\]

Now during form build, it gets the default argument as url parameter, and render results of query.Let's say my query result is an array of entity ids.

$entityids = array(1,2,3,4,5,6);

```
public function buildForm(array $form, FormStateInterface $form_state, $short_title = '') {

$query = \Drupal::entityQuery('mycustomentity');
$query->condition('colname', $short_title);
$entity_ids = $query->execute();

}

```

Now in form submit handler, I'm rebuilding form state like shown below:

class MyForm extends FormBase {

```
  protected $myvar;
  protected $step;
  protected $correct_ans;

  public function buildForm(array $form, FormStateInterface $form_state, $short_title = '') {

    $query = \Drupal::entityQuery('mycustomentity');
    $query->condition('colname', $short_title);
    $entity_ids = $query->execute();
    $i = 0;
    foreach ($node_storage as $nodeID=>$nodeData) {
       if ($i == $this->step)  {
echo $this->correct_ans;

       $correctAns = CategoryController::getCorrectAnswer($op,$entityid);
       $form['answer'][$i] = array(
            '#type' => 'hidden',
            '#value' => $correctAns,
      );
     }
    }

    }
public function submitForm(array &$form, FormStateInterface $form_state) {
$aString = $form_state->getValue('answer');
foreach ($aString[0] as $key1 => $value1) {

                         $this->correct_ans= $value1;

}
   $form_state->setRebuild();
   $this->step++;

    }

}

```

**Debugging results give:**

At first, when form gets loaded, it takes default parameter as argument from url == short\_title.

`print_r($entity_ids);` gives array(1,2,3,4,5) `print_r($correctans);` `echo "<br>";`gives arary(0=\>myanswer1)

**Hit Submit**

> array(1,2,3,4,5) array(0=\>myanswer1)
>
> array(1,2,3,4,5) array(0=\>myanswer1) array(0=\>myanswer2) array(0=\>myanswer1) array(0=\>myanswer3)

and `echo $this->correct_ans;` **always gives myanswer1**. **On every form submit form gets rebuild and $this-\>correct\_ans takes default array value which is array(0=\>myanswer1)**

**But I want,** On first submit, I get array(0=\>myanswer1), On second submit I want array(0=\>myanswer2), On third submit I want array(0=\>myanswer3) and so on...

Where I'm doing mistake?Please help.

# Answer
You are trying to store state values into a protected variable in the class. That will not work. You will have to store state values into the form.

So instead of using

```
$this->step

```

and other class properties to store values use

```
$form_state->set('step', $value);

```

to persist values between submissions.
> 1 votes

---
Tags: 8, forms
---


# Question
Title: How do you reorder an entity reference revisions field during hook_node_presave?
I am trying to reorder some paragraphs based on a text field within them on node save so the author does not need to maintain the alphabetical order manually, but when I save the node all values are lost. I tried matching the array from $node-\>get('field\_paragraphs')-\>getValue(), but that does not seem to work.

```
function mymodule_node_presave(NodeInterface $node) {
  if ($node->bundle() == 'page' && $node>get('field_paragraphs')->count() > 1) {
    $values = $node->get('field_paragraphs')->getValue();
    $entities = $node->get('field_paragraphs')->referencedEntities();
    uasort($entities, function ($a, $b) {
      return Unicode::strcasecmp($a->get('field_text')->value, $b->get('field_text')->value);
    });

    $new_values = [];
    foreach ($entities as &$entity) {
      $id = $entity->id();
      $new_value = [
        'target_id' => $id,
        'target_revison_id' => $entity->getRevisionId(),
      ];
      $index = array_search($id, array_column($values, 'target_id'));
      if (FALSE !== $index && isset($values[$index]['subform'])) {
        $new_value['subform'] = $values[$index]['subform'];
      }
      $new_values[] = $new_value;
    }

    $node->set('field_paragraphs', $new_values);
  }
}

```

# Answer
> 0 votes
You don’t need to populate an array with the IDs of the referenced entities. You just need to use a single line, the following one.

```
$node->set('field_paragraphs', $entities);

```

The code you are using can be simplified to the following one.

```
function mymodule_node_presave(NodeInterface $node) {
  if ($node->bundle() == 'page' && $node>get('field_paragraphs')->count() > 1) {
    $entities = $node->get('field_paragraphs')->referencedEntities();
    uasort($entities, function ($a, $b) {
      return Unicode::strcasecmp($a->get('field_text')->value, $b->get('field_text')->value);
    });

    $node->set('field_paragraphs', $entities);
  }
}

```

---
Tags: 8, paragraphs
---


title: How to save entity from a ajax form

text:
# Question
Title: How to save entity from a ajax form
I'm running Drupal 8.8.x

**The Problem**

Entity is not being saved when form is submitted through AJAX. Example:

**Build Form**

```
public function buildForm(array $form, FormStateInterface $form_state, EntityInterface $entity = NULL) {
  if($entity) {
    $this->entity = $entity;

    $form['element'] = [
      '#type' => 'textfield',
      '#title' => $this->t('My title'),
      '#name' => 'element',
      '#ajax' => [
         'event' => 'focusout',
         'callback' => [$this, 'myCallback'],
         'disable-refocus' => TRUE
      ]
    ];
  }

  return $form;
}

```

**Submit Form**

```
public function submitForm(array &$form, FormStateInterface $form_state) {
 $element = $form_state->getTriggeringElement()['#name'];
 $value = $form_state->getValue($element);

 $this->entity->set($element, $value);
 $this->entity->save();
}

```

I've confirmed $element and $value are the correct key and value. However, when I save the entity nothing happens. There is nothing updated in the database. And there are no errors emitted in the console or watchdog.

If anyone knows what could be the issue I'd appreciate some insight! :)

# Answer
> 1 votes
Drupal 8 doesn't cache Ajax forms anymore, so you can't get properties of the form object set in the initial form build. see Bypass form caching by default for forms using #ajax.

Forms are only cached as rendered form. Put the entity id in a hidden form element to load the entity before saving. Add the entity cache tag to the form if you use default values from the entity.

Or consider to switch from a general Form API form to an entity form.

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


# Question
Title: Change class on the div wrapper of a form element
Is there a way to add or change a class to a form wrapper (the div's) using the form api?

Or is that just done with the theme function ?

If so which theme function is used to change that?

# Answer
> 5 votes
You can override `theme_form_element()` normally if you want to change the theming globally. If you're interested in modifying just one specific form element then I'm aware of a couple of choices.

1. You can register a new theme function for the particular type of form element you're interested in (eg. textfield). You then create this theme function (based on the original, eg. `theme_textfield()`) but that doesn't call `theme('form_element', ...)` at the end (you could either handle both the wrapper and the element in the one theme function, or you could make a separate wrapper theme function and use that). Finally you add a `#theme` property to a particular form element, and that element will get your custom theming.
2. You can create a template file called `form_element.tpl.php` which just has the default behaviour of `theme_form_element()` and then use `hook_preprocess_form_element()` to add a template suggestion. Then you create the new template that matches the suggestion. You often hear people mentioning that templates are slightly slower than functions, and for such a frequently used theme call I can imagine people balking at using a template. I've never done any measurements for this myself however. Also, you need to have enough context at the preprocess stage to be able to make the suggestion.

# Answer
> 13 votes
You can use *wrapper\_attributes* property.

```
$form['example'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Example'),
  '#wrapper_attributes' => ['class' => ['wrapper-class']],
];

```

# Answer
> 5 votes
I know this is a super old thread, but I'v been learning how to alter form elements and add classes. I got around to making a custom module:

```
function yourtheme_custom_form_alter(&$form, &$form_state, $form_id) {
 case'webform_number_whatever':
   _yourtheme_form_add_wrapper($form['submitted']['yourfieldhere'], array('form-field-some-style', 'not-label', 'whatever-other-styles-you-want'));
 break;
}

function _yourtheme_form_add_wrapper(&$element, $classes = array(), $type = array('form-item', 'form-type-textfield'), $removeTitle = FALSE){
  $element['#prefix'] = '<div class="' . implode(" ", $classes) . '"><div class="' . implode(" ", $type) . '">';
  $element['#suffix'] = '</div></div>';
}

```

# Answer
> 3 votes
To Change the "wrapper" you need to override form\_element. Basically all form elements get rendered with the form\_element theme `theme_form_element($element,$value);` (form.inc file)

So to change how this renders your form elements you simply copy that function to your template.php folder and rename it to: `phptemplate_form_element($element,$value)`

now you can make any changes and they will be used instead of the original function

1. Copy `theme_form_element($element,$value);` from form.inc
2. Paste it into (your theme) template.php
3. rename it to: `phptemplate_form_element($element,$value)`
4. clear all theme cache
5. make whatever changes you want and they will be used.

# Answer
> 0 votes
Importantly, theme\_form\_element will only modify the direct parent wrapper div and this may not be the intended target for CSS effects.

\[Although not programmatic, if one simply wants to apply a class to a node field's top-wrapper (it's wrapper's, wrapper's, wrapper) one can I suppose use "Field group" module by selecting "Manage Fields" for a particular content type and select "Add new group" as a simple DIV. Then the label can be removed and desired classes assigned to the additional wrapper (but now we have even more wrappers) - with unlimited nesting\]

# Answer
> 0 votes
You could use

```
'#prefix' => '<div class="new_class">', '#suffix' => '</div>'

```

and this will wrap it around

# Answer
> 0 votes
Make wrapper attributes configurable!

Create your own form-element theme function in your theme... `sites/all/themes/MY_THEME/theme/form-element.theme.inc`

```
function my_theme_form_element($variables) {
  $element = &$variables['element'];

  $attributes = isset($element['#my_theme_wrapper_attributes']) ?
    $element['#my_theme_wrapper_attributes'] : array();

  ...

  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";

  ...
}

```

Then you can do stuff like this...

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['mail']['#my_theme_wrapper_attributes']['class'][] = 'form-field--inline';
}

```

# Answer
> 0 votes
There are come cases in which neither `#prefix/#suffix` nor `#attributes => array('class')` give the desired results. My particular case is adding a class to the ajax-wrapper div around a managed\_file element. `#prefix/#suffix` creates a new container and `#attributes/'class'` modifies the class of an inner element, not the outermost.

The normal outermost div is just

```
<div id="edit-doc1--XX-ajax-wrapper">

```

which is difficult to target in CSS. I can target `[id^="edit-doc"]` or `[id$="-ajax-wrapper"]` but both of these target more than just the elements I wanted.

The solution I came up with is to add a `#process` element to the form and manually manipulate the element's code. Here's the `#process` attribute added to the form item's declaration:

```
$form['doc1'] = array(
  '#type' => 'managed_file',
  '#process' => array('mymodule_managed_file_process'),
);

```

And here's the `mymodule_managed_file_process()` function:

```
function mymodule_managed_file_process($element, &$form_state, $form) {

  // Call the original function to perform its processing.
  $element = file_managed_file_process($element, $form_state, $form);

  // Add our own class for theming.
  $element['#prefix'] = str_replace(
    'id=',
    'class="managed-file-wrapper" id=',
    $element['#prefix']
  );

  return $element;
}

```

Relying on string substitution isn't very portable, so use `str_replace` at your own risk. This code, however, does indeed alter the outermost DIV to add the necessary class:

```
<div class="managed-file-wrapper" id="edit-doc1--XX-ajax-wrapper">

```

---
Tags: 6, forms
---


# Question
Title: How can you identify all nodes that use a certain paragraph type or template?
In Drupal 7, given a custom paragraph bundle and an associated template file, is there a way to list all the nodes using that bundle? Or, if it's any easier, a way to do the same for a specific module instead of a paragraph type?

A Drupal core module update (https://www.drupal.org/project/link/issues/3095484) broke a bunch of our links across our site, and while a workaround is available, I wanted to test it against all the existing nodes first.

# Answer
As runwithscissors suggested in his comment, this can achieved with a view.

1. Create a view that shows nodes
2. Add a relationship to the referenced paragraphs
3. Add a filter on the paragraph bundle (aka 'Paragraph Type')

Once the relationship is added, the bundle fields will be available as filter.
> 4 votes

---
Tags: 7, nodes, paragraphs
---


# Question
Title: How do use hook_views_pre_render() to modify view fields
Want to use hook\_views\_pre\_render() to modify a field in view based upon data in another field. Starting with this code:

```
function sbn_views_pre_render(ViewExecutable $view) {
  drupal_set_message($view->id());
    foreach ($view->result as $key => $value) {
    // How do I select fields I need?
    }
}

```

What I don't know how to do is select the fields I want to work with from the $view object.

Some of the things I've tried so far:

kint($value-\>\_entity-\>get('id')-\>value);

drupal\_set\_message($value-\>\_object-\>get('id')-\>value);

drupal\_set\_message($value-\>get('id')-\>get(0));

drupal\_set\_message($value-\>get('parent\_id')-\>getValue()\['0'\]\['value'\]);

Can someone tell me, or point me to documentation which will explain?

Thanks!

# Answer
> 0 votes
Found the answer:

```
// https://drupal.stackexchange.com/questions/272495/how-to-get-views-field-names-values-for-hook-views-pre-render
foreach ($view->result as $key => $value) {
  //- Get parent_id value
  $parent_id_value =  $value->_entity->parent_id->getValue()[0]['value'];
  //- Get parent_type value
  $parent_type_value =  $value->_entity->parent_type->getValue()[0]['value'];
  drupal_set_message($parent_id_value .' | '.$parent_type_value);
}

```

---
Tags: views, hooks
---


# Question
Title: How to change field attributes of Content Entity?
In a custom module, I have a content entity in which I have defined this field:

```
$fields['formheader'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Header'))
  ->setSettings([
    'max_length' => 255,
    'text_processing' => 0,
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => $weight,
  ])
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    'weight' => $weight,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

I'd like to change its type from string to string\_long and max\_length from 255 to 1024.
How can I do that without uninstalling my module, changing my source code and installing my module again (there is already content in this entity)?

# Answer
Finally with help from Jdrupal and this article, I made it work:

```
function amap_update_8001(&$sandbox)
{
  $entity_type_manager = \Drupal::entityTypeManager();
  $bundle_of = 'contract_type';

  $storage = $entity_type_manager->getStorage($bundle_of);
  $bundle_definition = $entity_type_manager->getDefinition($bundle_of);
//Sometimes the primary key isn't 'id'. e.g. 'eid' or 'item_id'.
  $id_key = $bundle_definition->getKey('id');
//If there is no data table defined then use the base table.
  $table_name = $storage->getDataTable() ?: $storage->getBaseTable();
  $database = \Drupal::database();
  $definition_manager = \Drupal::entityDefinitionUpdateManager();

//Store the existing values.
  $header_values = $database->select($table_name)
    ->fields($table_name, [$id_key, 'formheader'])
    ->execute()
    ->fetchAllAssoc($id_key);

//Clear out the values.
  $database->update($table_name)
    ->fields(['formheader' => NULL])
    ->execute();

//Uninstall the field.
  $field_storage_definition = $definition_manager->getFieldStorageDefinition('formheader', $bundle_of);
  $definition_manager->uninstallFieldStorageDefinition($field_storage_definition);

//Create a new field definition.
  $new_formheader = BaseFieldDefinition::create('string_long')
    ->setLabel(t('Header for Form'))
    ->setSettings([
      'max_length' => 1024,
      'text_processing' => 0,
    ])
    ->setDefaultValue('')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string_long',
    ])
    ->setDisplayOptions('form', [
      'type' => 'string_textarea',
    ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

//Install the new definition.
  $definition_manager->installFieldStorageDefinition('formheader', $bundle_of, $bundle_of, $new_formheader);

//Restore the values.
  foreach ($header_values as $id => $value) {
    $database->update($table_name)
      ->fields(['formheader' => $value->formheader])
      ->condition($id_key, $id)
      ->execute();
  }

  drupal_flush_all_caches();

  \Drupal::messenger()->addMessage('Module AMAP Update # 8001 was executed successfully.');

}

```
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How to add Jquery Validation to Custom form and set error to field?
I want to implement client side validation using jQuery on my custom form.

I have enabled clientside validation contributed module

I have successfully attached custom js file using following code:

```
 $form['#attached']['library'][] = 'custom_form/cl-validation';

```

And in the JS file I have written below code:

```
(function ($, Drupal) {
  Drupal.behaviors.custom_form = {
    attach: function (context, settings) {

        var selectedCountry = ''

        $("#country").change(function(){
          selectedCountry = $(this).children("option:selected").val();

        });

        $('#user-number-value').keyup(function(){
              $(this).val($(this).val().replace(/(\d{2})|([a-z]{2})\-?/,'$1-'))
        });

         $("input#user-number-value").focus(function() {
            if(selectedCountry == undefined || selectedCountry == '') {
                $('#user-number-value').va('')
               // I want mark country dropdown as red and show a error
            }
        });

    }
  };
})(jQuery, Drupal);

```

I am not getting how to do this using jquery and stop form submission.

Any help?

# Answer
If the form field is empty you need to stop propagation of the parent form. This should be what you need.

```
 countryValidation = function() {
    // Lets use a function so we can check the field
    $country = $('#country');
    if ($country.val() === '') {
      return false;
    } else {
      return true;
    }
  }

  $('#user-number-value').on('focus', function(){
    if(countryValidation() === false){
      // If the field check comes back false on focus lets add a class
      $('#country').addClass('invalid');
    };
  });

  $('#country').on('change', function(){
    // This will remove the class when the user fixes the error
    if(countryValidation() === true) {
      $('#country').removeClass('invalid');
    } else {
      $('#country').addClass('invalid');
    }
  });

  $('form').on('submit', function(e) {
    if(countryValidation() === false){
      // when the field comes back invalid lets add the class
      $('#country').addClass('invalid');
      // this will prevent the form from submitting
      e.preventDefault();
    };
  });

```
> 1 votes

---
Tags: 8, forms
---


title: Sort by taxonomy weight

text:
# Question
Title: Sort by taxonomy weight
I have a content type 'Member' with a field referring to taxonomy term called 'Member role' which is a multi value field. Each member may have up to 3 member roles.

I have created a view to display members which sorted by taxonomy term weight with reference to taxonomy field. But the problem is each member repeats 3 times in the view result page.

My question is how to remove duplicates and only sort by last value in the multi value field(Member role).

# Answer
> 0 votes
Below are a couple of things you can try to reduce duplicates caused by a multi-value field. Results will vary depending on your particular view.

### 1. Use aggregation

Under "Other" in Advanced options, enable *Use aggregation*.

Locate the offending field under "Sort criteria". Click on *Aggregration settings*, then select **Aggregation type:** *Maximum*.

### 2. Filter by delta

Under "Filter criteria", add the delta equivalent of your multi-value field; e.g. if your field is "field\_artist\_bio", there should be another field available called "field\_artist\_bio:delta".

Add the field. Set **Operator:** *is equal to*, **Value:** *0*.

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


title: Consume external API from custom block

text:
# Question
Title: Consume external API from custom block
I am currently writing a custom module - block plugin for **Drupal 8** \-
**How do i go about consuming/sending external API data and displaying them using blocks?**

Is this the standard way - consume/send external API data via plugin directly or through a controller and output it to a twig template? **If so, how do i send data from controller to a custom plugin block?**

Any suggestion is welcome. Thank you.

# Answer
> 0 votes
I'd do it this way:

* Create a custom module
* Create a class inside the `src` folder that consumes the API
* Create a custom block inside your module: call the class there

Mostly it is better to fetch f.e. each hour and save the api data to custom entities. In this way you can cache the content in the block which enhances performance.

---
Tags: 8, blocks, plugins
---


# Question
Title: How can I use a replacement pattern in a custom field?
I just created a new custom field in a view, but I would like to use replacement patterns in that field. Is it possible to do this?

```
class CustomButtonField extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function usesGroupBy() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    // Do nothing -- to override the parent query.
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['target'] = ['default' => FALSE];
    $options['class'] = ['default' => FALSE];
    $options['text'] = ['default' => FALSE];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    $form['target'] = array(
      '#title' => $this->t('The target id of the button'),
      '#type' => 'textfield',
      '#default_value' => $this->options['target'],
    );

    $form['class'] = array(
      '#title' => $this->t('The class of the button'),
      '#type' => 'textfield',
      '#default_value' => $this->options['class'],
    );

    $form['text'] = array(
      '#title' => $this->t('The text of the button'),
      '#type' => 'textfield',
      '#default_value' => $this->options['text'],
    );

    parent::buildOptionsForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
    return [
      '#theme'  => 'custom_button',
      '#target' => $this->options['target'],
      '#class'  => $this->options['class'],
      '#text'   => $this->options['text']
    ];
  }
}

```

How can I use replacement patterns in `$form['text']`?

# Answer
> 1 votes
Take a look to `\Drupal\views\Plugin\views\field\FieldPluginBase::renderText`

```
/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
  $tokens = $this->getRenderTokens($this->options['text']);
  return [
    '#theme'  => 'custom_button',
    '#target' => $this->options['target'],
    '#class'  => $this->options['class'],
    '#text'   => $this->viewsTokenReplace($this->options['text'], $tokens),
  ];
}

```

---
Tags: views, 8
---


title: Drupal 8 migrate fields not filled

text:
# Question
Title: Drupal 8 migrate fields not filled
I'm trying to migrate content to D8 site from sql source. In my migrate\_plus.migration.node\_article.yml config file I've following:

```
id: node_article
label: Article Migration
migration_group: node_migration
source:
  plugin: node_article
  bundle: node
destination:
  plugin: entity:node
process:
  uuid: uuid
  title: title
  type:
    plugin: default_value
    default_value: article
  field_seo_title: title
  field_teaser_text: title
migration_dependencies: {}
dependencies:
  enforced:
    module:
      - my_article_import

```

(field\_seo\_title is a textfield) and NodeArticle.php:

```
class NodeArticle extends SqlBase
{

    public function query()
    {

        //query code ommited
    }

    public function fields()
    {
        $fields = [
            'uuid' => $this->t('Unique Unique Identifier'),
            'title' => $this->t('Title'),
            'field_teaser_text_value' => $this->t('field_teaser_text_value'),
            'field_seo_title_value' => $this->t('field_seo_title_value'),
        ];

        return $fields;
    }

    public function prepareRow(Row $row)
    {
        return parent::prepareRow($row);
    }

    public function getIds()
    {
        return [
            'nid' => [
                'type' => 'integer',
                'alias' => 'n',
            ],
        ];
    }

}

```

When I run migration, node is created, title get filled but all other fields are empty no matter what data I try to import. I spent almost a day trying to figure out why but running out of ideas. Does anyone have an idea what could be an issue please? Thanks

# Answer
> 1 votes
Assuming your source class works, there are two things I'm spotting:

A)
Do not prefill internal entity keys like `nid`, `uuid` or `revision_id` in the migration YML, the Migrate module will set them for you. Manually setting them is not required at best, and a potential cause of errors at worst.

B)
If your text fields are plain text fields, then your YML should be correct. But if your text fields are formatted text fields, then you also have to fill the `format` sub column for those text fields:

```
  process:
    ...
    field_formattedtext/value: source_field
    field_formattedtext/format:
      plugin: default_value
      default_value: my_format_eg_basic_html
    ...

```

---
Tags: migrations
---


# Question
Title: How to pass parameters by reference to a batch?
I need to process a parameter in a batch function where the result will be kept after the function ends and it should be then passed in the finished function of the same batch. Is there a way to pass the parameters by a reference, so that any changes to that parameter are saved?

Example:

```
$params = [$a, $b];
$finishedParams = [$a, $b];
$batch = ['title' => 'Sample processing batch',
          'operations' => ['someFunction', $params],
          'finished' => ['finishedFunction', $finishedParams]
         ];
...
public static function someFunction(&$a, $b){
    $a = 'somethingChanged';
}
public static function finishedFunction($success, $results, $operations){
   // Use $a variable when somethingChanged after the batch process.
}

```

# Answer
> 3 votes
Alfred is right. You can achieve that by using the $context parameter.

```
public static function someFunction($a, $b, &$context) {
  // Store data in $context['results'] entry.
  // my_var will keep that value.
  $context['results']['my_var'] = 20;
}

```

---
Tags: batch-operations
---


title: Create media from blob

text:
# Question
Title: Create media from blob
I am receiving a payload with blob files.

I would like to store them as files and create a media entity.

Here's the code I have to create the Media object

```
 if (!empty($payload['blobFile'])) {
  $name = str_replace(' ', '_', $payload['fileName']);
  $file = file_save_data($payload['blobFile'], 'public://' . $name, FILE_EXISTS_REPLACE);
  $content['field_media_file'] = ['target_id' => $file->id()];
}
$this->entityTypeManager->getStorage(....

```

It successfully creates the media content and attach a file to it.

Unfortunately the file is still blob I don't see a pdf or similar.

# Answer
> 2 votes
A file that comes in from a browser's Web API as a Blob is probably base64-encoded. PHP will not decode files in the POST or GET parameters. It is up to the PHP application to decode the file before saving.

```
if (!empty($payload['blobFile'])) {
  $name = str_replace(' ', '_', $payload['fileName']);
  $file = file_save_data(base64_decode($payload['blobFile']), 'public://' . $name, FILE_EXISTS_REPLACE);
  $content['field_media_file'] = ['target_id' => $file->id()];
}

```

It might also be useful to check if the binary is actually a PDF before saving, but that could be done in different ways based on opinion (loading via a PDF library, checking file headers, virus/malware scan).

---
Tags: 8, media
---


# Question
Title: Fully display only most recent post on front page, furl the others
Currently my Front page will only show a teaser for all my new posts.

I know that I can go to `Structure > Views > Frontpage` and change it to `show Content | Full` which will show the full post of every post on the front page.

What I would like to do though is show the full post of only my most recent post, and then a teaser of all the others.

Is it possible to do this?

# Answer
> 1 votes
You can render a views block within another views page. E.g. you want to show 10 nodes in total, and 1 of them in full mode:

1. Duplicate the existing view display as a new display of type "block". (Do not duplicate the entire view, only the sub-display by using "Duplicate as block").
2. In the original page display, in the Pager section, limit the number of items to 1.
3. In the original page display, in the Format section, set the view mode to full.
4. In the new block display, in the Pager section, limit the number of nodes to 9 and set the offset to 1.
5. In the new block display, in the Formatw section, set the view mode to Teaser. While changing the Format make sure to change the settings only "for: this block (override)" and not "for: All displays".
6. In the orignal page display, in the Footer section, add a "View area" and place the newly created block display. Here also change those settings only "for: this page (override)".

---
Tags: views, 8
---


# Question
Title: How to programmatically add a "more" link?
In the Views UI (in the center column), we can select "More link" which provides a checkbox to "Create more link." Selecting this returns a link for more results of the view.

How would I programmatically add this "more" link? That is a link to all results of a Drupal 7 view?

# Answer
Wow -3 rating? This was intended to be an authentic question.

Not ideal, but my solution was to render a static link in the View's footer:

```
   // Render "more" link in footer
    $footer_options = array(
    'label' => t('Footer text'), // Administrative label.
    'content' => '<a href="/link/to/display">View All Events</a>', // Content of footer text.
    'format' => 'filtered_html', // Format of text.
    'empty' => 0, // 0 hides footer if view is returning no results; 1 sets footer to always display.
  );
  $view->add_item('default', 'footer', 'views', 'area', $footer_options);
  }
}

```
> 0 votes

---
Tags: 7, views
---


title: Don't cache custom Front Page domain

text:
# Question
Title: Don't cache custom Front Page domain
I'm working on a module that shows a different frontpage per role. I have three frontpages:

1. the base `www.domain.nl` for `anonymous` users, set in the basic site settings
2. for users with `role_1` they go to `sub1.domain.nl\dashboard`
3. for users with `role_2` they go to `sub2.domain.nl\dashboard`

I'm almost there but the frontpage url is set in cache (I think) therefor when I login I get the right frontpage. So I have `role_1` en go to `sub1.domain.nl`. Now when I logout I want to go back to `www.domain.nl` but I still get redirected to `sub1.domain.nl`. Even when I close the browser and return to the site I still get back to `sub1.domain.nl`.

So my question is how can I make sure this response is cleared from cache after loggin out or is not even cached at all? What is the best method to deal with this?

*My code till now:*

**mymodule.services.yml**

```
services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\FrontpageSubscriber
    tags:
      - {name: event_subscriber}

```

**src/EventSubscriber/FrontpageSubscriber.php**

```
<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\TrustedRedirectResponse;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class FrontpageSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public function checkFrontRedirection(GetResponseEvent $event) {
    $current_path = \Drupal::service('path.current')->getPath();
    $front_uri = \Drupal::config('system.site')->get('page.front');
    $front_alias = \Drupal::service('path.alias_manager')->getAliasByPath($front_uri);
    $current_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    $isFrontPage = \Drupal::service('path.matcher')->isFrontPage() || $front_alias === $current_alias;

    if ($isFrontPage) {
      $hasRole1 = \Drupal\user\Entity\User::load(\Drupal::currentUser()
        ->id())->hasRole('role_1');
      $hasRole2 = \Drupal\user\Entity\User::load(\Drupal::currentUser()
        ->id())->hasRole('role_2');

        if ($hasRole1) {
          $domain_url = 'https://sub1.domain.nl/dashboard';
          $response = new TrustedRedirectResponse($domain_url);
          $event->setResponse($response);
        }

        if ($hasRole2) {
          $domain_url = 'https://sub2.domain.nl/dashboard';
          $response = new TrustedRedirectResponse($domain_url);
          $event->setResponse($response);
        }
     }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkFrontRedirection');
    return $events;
  }
}

```

# Answer
> 5 votes
Could be a caching issue within the browser, Drupal or both. For the browser set cache headers in the response, see https://drupal.stackexchange.com/a/278703/47547.

For Drupal caching add a cache context `user.roles`:

```
$response->getCacheableMetadata()->addCacheContexts(['user.roles']);

```

Furthermore it is recommended to execute a redirect event subscriber only on a master request, this helps to prevent redirect loops:

```
public function checkFrontRedirection(RequestEvent $event) {
  if (!$event->isMainRequest()) {
    return;
  }
  ...
}

```

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


title: Handling data from form in modal dialog

text:
# Question
Title: Handling data from form in modal dialog
I'm building a tool that contains a few clickable regions. Each region has a link with `class="use-ajax" data-dialog-type="modal"` pointing at a custom form route.

Everything is working great and I'm able to get the data from the form and store it. I, however, need the user's selection in this modal form to be reflected in the region they initially clicked.

I'm at a loss aside from storing their selections in localStorage or something and populating that region when they close each modal. That seems a little hacky though. Is there a cleaner way of accomplishing this that I'm missing?

```
<div class="region">
    <a class="use-ajax" data-dialog-options="{"width":550, "dialogClass": "my-region-class" }" data-dialog-type="modal" href="/route/to/custom/form">
      <div class="content">
      Click to select
      </div>
    </a>
  </div>

```

# Answer
> 2 votes
You can pass down your region's ID as parameters to your route. For example:

```
<a class="use-ajax" data-dialog-options="{"width":550, "dialogClass": "my-region-class" }" data-dialog-type="modal" href="/route/to/custom/form/this-region">...</a>

```

As explained here you can add arguments from the route to your form.

On the buildForm method you can have something like this

```
public function buildForm(array $form, FormStateInterface
  $form['button'] = [
    '#type' => 'button',
    '#value' => $this->t('Submit this form'),
    '#name' => 'ajax_trigger',
    '#ajax' => [
      'callback' => '::updateRegionAjaxCallback',
      'wrapper' => $region, // Assuming $region is the argument passed down.
      'method' => 'replace',
      'effect' => 'fade',
      'event' => 'click',
    ],
  ];
}

```

Later your callback method could look like.

```
public static function updateRegionAjaxCallback(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new AppendCommand(NULL, [
    // Your render array with the data to be displayed.
    '#cache' => [
      'max-age' => Cache::PERMANENT,
      'contexts' => ['url'],
    ],
  ]));

  return $response;
}

```

This should work but keep in mind that will be best capture the form submit and triggering a custom AJAX event.

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


# Question
Title: Site broken after upgrading with Pathauto < 8.x-1.6
I recently upgraded to Drupal 8.8. Unfortunately I missed the memo on needing to upgrade Pathauto first and now my site is broken. Most pages give the message "The website encountered an unexpected error. Please try again later."

I can get to /user and log in with an admin account, and I can get to /update.php which tells me "The Pathauto module is not compatible with the current version of Drupal core. Update the Pathauto module to 8.x-1.6 or later." and does not give me the option to continue to database updates.

I can't get to many other pages, and notably can't get to /admin/modules where I would normally upgrade a specific out of date module like Pathauto.

Do I have any other options besides wipe my site and restore from a backup? Even if I can figure out how to upgrade Pathauto at this point, I'm not clear if that's likely to fix the issue.

Thanks.

# Answer
Based on the comments above from leymannx, I've manually uploaded Pathauto 1.6 to my site via FTP. Returning to /update.php, I got the option to update the database and that worked and my site is back up again.

Note: The first time I tried this, I renamed the old Pathauto module folder to "pathauto\_old", and uploaded the new version to a newly created folder just called "pathauto", and that did not work. update.php continued to report and out of date Pathauto. After that, I deleted both folders, re-uploaded pathauto 1.6, and then it worked.
> 2 votes

---
Tags: 8, updating
---


# Question
Title: How to add as exposed filter a product attribute in Commerce's orders view?
I have a drupal 8 commerce website. The Orders page is a view that comes with commerce where all the orders are listed. Is it possible to add/create ( on the website or programatically ) an exposed filter based on a PRODUCT ATTRIBUTE to show all the orders containing a value of that product attribute?

For example: for a product attribute called ORIGIN, I would like an exposed filter in the orders view that would allow me to choose between 2 values: Los Angeles or San Francisco.

Some orders will show up in both because they will have different products with different ORIGIN value product attributes.

I tried to modify the orders view but I couldnt find any product attributes nor a relationship to products. I tried to add a relationship to order item but that didn't help expose any of the product attribute fields.

# Answer
Product's attributes are set through the product variation. You need to add the Variations through a relationship and you will have attributes available there.

After that your attributes can be added as exposed filters.

Sorry I don´t have any English sites available but pay close attention to captures.
> 1 votes

---
Tags: commerce
---


# Question
Title: How to not include page titles in the webform included email values?
My webform has pages and sections in a webform. The title of the page is not printed out on screen, but it is printed out in the email. The page name was setup as being the same as the section resulting in the email sent having duplicate headings as follows

The form has pages and sections with the form build looking like

I'm using a twig template to print out the results. I could print out each field/title individually however I'd rather just use the 'included email values' functionality. This would make my webform more maintainable. The headings are not in the list of included email values.

Is there a way to manage the headings using this interface? An alternative would be to use inline css on the email. e.g. .x\_webform-section-wrapper \> h2 {display:none}. I'm not sure all the downstream applications will cope with this.

# Answer
This should be as easy as changing the wizard page's display settings, but you found a bug.

Issue #3106037: Allow a multi-step wizard page's display to be customized

Once you apply the patch, in the page element's 'Advanced' you can change how the page is displayed via HTML and text. You can use Twig to just render the child element.
> 3 votes

# Answer
I made the label for the wizard page non-breaking-space ` `. It is ugly but it works. Luckily we didn't need the page headings.
> 0 votes

---
Tags: webforms
---


# Question
Title: How to get the url from a link field in preprocess function
* I have a content type event.
* It has a link `field field_event_location_link`
* Both the link text and url are optional

By default Drupal uses the url as the title if there is no title typed in.

I want to show 'Location' if the title is not filled in.

How can I use a preprocess function to see if there is a title, and if not, use my string.

I tried ...

```
function my_module_preprocess_field(&$variables) {
  if ($variables['field_name'] == 'field_event_location_link') {
    if ($variables['items'][0]['content']['#title'] == '') {
     $variables['items'][0]['content']['#title'] = 'Location';
    }
  }
}

```

But it doesn't work and I think it's because by the time I get to that point, Drupal has already used the uri for the #title.

**Question:** Can I catch it before that? Or can I get a variable for the URL and use that variable in the `''` above? Should I be checking if something is empty...?

# Answer
If you inspect with `$variables['items'][0]['content']` with Devel kint

```
kint($variables['items'][0]['content']);

```

> But it doesn't work and I think it's because by the time I get to that point, Drupal has already used the uri for the #title.

Correct, so all you gotta do is check if the title is equal to the url utilizing Url::toString.

```
  if ($variables['field_name'] == 'field_event_location_link') {
    $link_url = $variables['items'][0]['content']['#url']->toString();
    if ($variables['items'][0]['content']['#title'] == $link_url) {
      $variables['items'][0]['content']['#title'] = 'Location';
    }
  }

```
> 0 votes

---
Tags: 8
---


# Question
Title: How to send mail with third party domains?
I'm using mailsystem and Swift Mailer. Instead of paying for a professional service or self-hosting, I'd like my site email to be sent using my hotmail or another domain I control.

Eg let's say my Drupal domain is **mydomain.com**. I want the site mail address to be **somethingelse@hotmail.com** or **me@somethingelse.com**

Is this possible and does it need special configuration?

All my attempts to send mail using Outlook's STMP server or myother domain's SMTP service have led to refused connections.

# Answer
It is possible to send email via SMTP using Outlook's SMTP server. Make sure you have set Swiftmailer to send mail via SMTP.

* **SMTP server:** smtp-mail.outlook.com or smtp.office365.com
* **Port:** 587
* **Encryption:** TLS

Use your Hotmail address and password to log in. You'll probably need to enter your Hotmail address under "Configuration" -\> "Basic site settings".

Your web hosting provider may block outgoing SMTP ports. Check with their support to make sure.

More information:
> 0 votes

---
Tags: 8, emails
---


# Question
Title: How to access link fields (url and text) value separately in views template?
My views block has a *Link* field named `field_link`, attached to a *Content Type* named `products`, and I'm trying access link field values(url and text) separately in views template `views-view-unformatted.html.twig`.

Following code gives the formatted html.

```
{{ row.content['#view'].style_plugin.render_tokens[ loop.index0 ]['{{ field_link }}'] }}

```

formatted html:

```
<a href="example.com/product-list" tabindex="-1">View Products</a>

```

But I want to access the link fields(url and text) value separately. Any help will be appreciated.

I am not able to check `row` variable via kint/dump as I am getting `PHP Fatal error: Allowed memory size of 1073741824 bytes exhausted`

# Answer
> 3 votes
The Easy way in Views UI add field\_link 2 times.

in 1) Exclude from display, Select url only, and Show url as plain text. which will give you the url only.

in 2) Exclude from display, and REWRITE RESULTS -\> Strip HTML tags which will give you the title only.

Then in a custom field you can use twig URL: {{ field\_link }} Url Title: {{ field\_link\_1 }}

then in your custom template you can use them ...

Option 2) almost as easy create a custom field formatter based on Drupal\link\Plugin\Field\FieldFormatter\LinkSeparateFormatter.php

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


# Question
Title: How do I add fields to the sidebar menu when creating/editing nodes?
I would like to add to the sidebar menu on the create/edit node pages. How would I do this?

I would like to do this in order to make the content creating/editing a little cleaner and easier to understand for content editors.

See attached pic...

Thank you.

# Answer
> 4 votes
The latest version of Field Group module supports putting fields into the sidebar (at least for nodes).

Field Group version \>= 3.0-rc2, containing issue 2652642

# Answer
> 4 votes
How todo it custom in code such as in a hook\_form\_alter

```
$form['something'] = [
  "#title" => t('@title', ['@title' => 'My Title']),
  "#type" => "details",
  "#group" => "advanced",
  "#weight" => 50,
];

// Add fields to the group.
$form['something']['text'] = [
  "#title" => t('@title', ['@title' => 'test']),
  "#type" => "textfield",
  "#group" => "advanced",
  "#weight" => 50,
];

```

---
Tags: 8, nodes
---


# Question
Title: How can I get the currently submitted form state in a block on the same page?
How can I retrieve the currently submitted and validated form state?

Please assume the following scenario.

A page has a form on it created using the form API. The data in the submitted form is transient. In other words it is not saved or stored in any way.

The form is created by a module I do not control and therefore I should not alter the codebase.

On the same page as the form is a block (mine) which displays data based on the form submission.

I want to get access to the validated data from the anonymous user submitted form from within the block plugin code.

The form does all the necessary validation of the user submitted data. I do not want to replicate this validation so I need to get access to the validated form\_state so I can extracted the submitted values.

I cannot see a way to retrieve the form\_state object from the current request.

How can this be done?

# Answer
> 1 votes
As with most things you are learning. The answer is often simpler than first thought.

To resolve my issue I was able to use `hook_form_alter` and implement my own submission handler.

From here I was able to disable the redirect to prevent the page reloading.

Once redirect was disabled then my block plugin was able to get access to the form and use the validated results within it.

My block build for demo purposes contained the following

```
public function build() {

  // Get the current form.
  $form = \Drupal::formBuilder()->getForm('Drupal\modulename\Form\moduleForm');

  return [
    '#markup' => "<pre>" . print_r($form, TRUE) . "</pre>",
  ];
}

```

The important point is `\Drupal::formBuilder()->getForm('name')` returns the cached form results and therefore does not require any further validation.

This can be verified by checking `$form['#validated'] == 1`.

---
Tags: 8, forms, blocks
---


# Question
Title: How to open a link in ctools modal by clicking a views row in table format?
I want to open a page in ctools modal. This works for me.

```
<a href="/my-page/nojs" class="ctools-use-modal">Click</a>

```

But now I want to open the same page in ctools modal by clicking the views row. The views is in table format.

```
<tr class="ctools-use-modal clickable" onclick="window.location='/my-page/nojs'">

```

It opens the link but not in ctools modal. I am using bootstrap theme.

I noticed that after page load there is another class added to the anchor tag `ctools-use-modal-processed` which is not added to the table row.

And we can't use an anchor tag before or after the `tr` in html table. We can only use it inside a `td`.

How can I achieve this?

# Answer
I used this code and it solved my problem.

```
// Bind table rows that will open ctools modals to the appropriate function.
      $('tr.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);
        // Create a drupal ajax object
        var element_settings = {};
        if ($this.attr('href')) {
          element_settings.url = $this.attr('href');
          element_settings.event = 'click';
          element_settings.progress = { type: 'throbber' };
        }
        var base = $this.attr('href');
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
      });

```

and table row like this

```
<tr class="ctools-use-modal" href="/my-page/nojs">

```

Hope it will help someone.
> 0 votes

---
Tags: 7, views, modal-dialogs
---


title: Node content is not shown

text:
# Question
Title: Node content is not shown
I installed DrupalGap. Everything works fine so far, except that the node body is not displayed. I have none of the mentioned interfering modules installed. I also tried with a fresh Drupal 7 installation in a new test environment with the same result.

I ask for advice or hints.

Note: values are handed over. I can display the body instead of the title. But after clicking a node title, in the sub sequent page only the titel and the comments are shown.

Additional information: the edit mode of a node shows the html content. Only the view does not show the content (body)

10th of Jan 2020: I made a clean Drupal 7.69 installation with minimum modules (in order to exclude module interferences) with DrupalGap 7.x-1.17 on my localhost. Same effect - not showing the node body in View mode. I wonder what configuration the DrupalGap demo does have? There it works.

# Answer
> 1 votes
The problem was that the Body field was not added to the DrupalGap Display Mode for the content type:

> By default, there are no fields displayed using the DrupalGap Display Mode. We need to specifiy which fields, labels and formats will be used when our nodes are displayed in the mobile app. Do this for each content type.

---
Tags: 7, nodes, javascript
---


# Question
Title: csv file imports only the last row when imported in drupal 8 webform
I have a csv file which contains the entries from drupal 7 webform. I uploaded the csv file in drupal 8 webform. It imports the data, but only the last entry is shown in the drupal 8 webform's results.

This is the csv file: columns A-D : IP Add, UUID, Phone Number, Email. (dummy entries).

When importing the mapping from the csv file, it shows me the below options:

I select the matching columns on the destination(submission) and then click import. After importing this is what drupal displays:

Only the last row from the csv file is updated in the webform.

# Answer
The UUID for all your CSV records is 1 and when they are being imported, each row is overwriting the previous row. You also need to include the column headers as the first row in the CSV.
> 0 votes

---
Tags: webforms
---


# Question
Title: How can I remove Features modules from a site without affecting functionality?
I have inherited a site that makes heavy use of Features, and this constrains what I can do to permissions and creates dependencies that don't otherwise exist. Something as simple as turning off the overlay becomes a mystery.

Is there some way I can remove these features and give back control to the database and to dependencies declared in non-Feature modules? I'd sure like to be able to adjust permissions by visiting the usual permissions UI and making the change as per usual.

I see there is a Features Tools module that appears relevant, but it does not seem to address things like roles and permissions. And it's a bit discouraging to think that an additional module might be necessary just to de-Features a site.

# Answer
> 0 votes
When you are absolutely sure there is no custom code in the feature module you can safely recreate the feature by going to /admin/structure/features and then change permissions and/or disable modules such as the Overlay module that are declared as a dependency in the feature.

You can recreate the feature and remove the unwanted components:

1. Go to /admin/structure/features
2. Click the 'Recreate' button next to the feature
3. Uncheck all dependencies or other components that you don't want in the Feature.
4. Click the 'Download feature' button.
5. Replace the Feature module in your modules folder.

When you are not sure there is any custom code in the feature module do this on a local environment and check all changed code via Git to make sure only the components you deselected are removed from the feature module.

---
Tags: 7, features
---