-
Drupal + Twig: Render Taxonomy Terms and Comma-Separated List
Here’s a snippet that renders the terms in a multi-value taxonomy reference field (in a node template) as plain text items separated by commas. Yes, you could get the string into the desired format using PHP, but I wanted to try to do it with only Twig. The result is moderately readable.
Twig Code:
For a taxonomy term reference field called field_pub_tr_res_committees
123456789101112<dt class="pub__rescomms">{% trans %}Research Committee(s){% endtrans %}</dt><dd class="pub__rescomms">{%- for item in content.field_pub_tr_res_committees['#items'] -%}{%- if loop.first -%}{{- item.entity.name.value -}}{%- elseif loop.last -%}{{- ' and ' ~ item.entity.name.value -}}{%- else -%}{{- ', ' ~ item.entity.name.value -}}{%- endif -%}{%- endfor -%}</dd>Output:
If 1 value: My first term
-
Migrating Specific Fields in a D8 Migration
I recently needed a way to update the value of a single field of a D7 to D8 node migration.
The client was already updating the migrated content so I had to be careful with what I migrated.
The entity destination plugin has a wonderful configuration option that allows you to specify which fields you want to migrate. Search the code here for overwrite_properties.
Here’s how I used this to ignore every field except two:
12345destination:plugin: entity:nodeoverwrite_properties:- field_tax_groups- field_tagsI tested this by editing a node’s title, subtitle, field_tax_groups, and field_tags values. I ran the migration and the edits were preserved on the title and subtitle fields as expected.
-
Migrating a Drupal 7 User Profile2 Image Field to a Drupal 8 User Image Field
Consider this scenario:
- Drupal 7 site contains Profile2 profile called person with image field called field_oldsite_person_image.
- Users each have a profile2 profile associated with their account.
- Drupal 8 site has an image field called field_newsite_user_photo on the user entity itself.
If you need to migrate the image field from the Drupal 7 profile to the Drupal 8 user entity you can extend the d7_user plugin and query for the additional field data. I’m executing an extra query for each user (because the code is in the prepareRow() method), rather than attempting to pull all of the profile data as part of the query in the query() method of the class.
First, create a file in your module like /modules/custom/mysite_migrate/src/Plugin/migrate/source/MysiteUser.php that extends the d7_user plugin:
- Drupal 7 site contains Profile2 profile called person with image field called field_oldsite_person_image.
-
Quick Tips for a Drupal 7 to Drupal 8 Migration
Here are a few quick tips for a Drupal 7 to Drupal 8 migration. I will add more over time; admittedly it’s pretty lame right now!
For general Drupal 8 Migrate API tips, you may also want to check out my other post: Drupal 8 Migrate – Tips and Tricks
Source Plugins
If you’re using a source plugin like d7_user or d7_node it will help you understand what’s happening if you view the source code for the plugin. Pay close attention to the query(), prepareRow(), and fields() methods.
-
Only Migrating Published Nodes in a D7 to D8 Migration
I’m not going into much detail here but hopefully this helps someone.
If you need to migrate only published nodes you can extend the d7_node plugin and add a condition to the query.
First, create a file in your module like /modules/custom/mysite_migrate/src/Plugin/migrate/source/MysiteNewsNode.php that extends the d7_node plugin:
-
Using GROUP_CONCAT to Combine Rows in a Drupal Query
Recently I was working on a D7 to D8 migration. I was trying to import news items and their taxonomy terms (among many other things). To make things simple I wanted the query results to have (for each node) a single field that contained a comma-separated list of taxonomy terms which I could then explode during the row processing. Using GROUP_CONCAT we can achieve this! Let’s break it down:
The Drupal 7 site has the following structure (focusing on the important bits for this blog post):
123-- News Item (news_item) <content type>---- Categories (field_categories) <field collection>------ Audience (field_term_audience) <taxonomy reference; unlimited values>The migration relies on the d7_node migrate source plugin, which basically queries for nodes of a specific type. The query object looks like this (simplified for this blog post):
-
User-chosen Field Output Styles in 5 minutes using Display Suite
I’m working on a site that has a “Statistics” paragraph bundle. The output looks like this:
The specification calls for the content author to be able to choose between a few different visual styles for the header (title), shown as Statistics: 3 Up Feature Ipsum Sit H2 in the screenshot above.
The simplest way to achieve this is to add a field to the paragraph bundle:
123456789Name: Header StyleMachine name: field_header_styleType: List (text)Allowed number of values: 1Default value: Visually normalRequired: TRUEAllowed values:small|Visually smallnormal|Visually normalNote that the key (key|value) needs to work as a css class.
-
Basic HTTP Authentication in Drupal Site Using settings.php
Here’s a quick and painless way of preventing public access to a Drupal site using settings.php (or settings.local.php).
I’ve been using this for development and staging sites that I want to keep private.
If you want this to be available to all settings*.php files you should put this near the top of your settings.php file:
123456789101112131415161718192021222324/*** Locks the site via basic http auth.** D7: if (!drupal_is_cli())* D8: if (PHP_SAPI !== 'cli')** @param array $users* Array of users e.g., ['user1' => 'pass1', 'user2' => 'pass2'].** @see https://agileadam.com/2018/04/basic-http-auth-drupal-site-using-settings-php/*/function lock_with_basicauth($users) {if (PHP_SAPI !== 'cli') {$valid_users = $users;$valid_usernames = array_keys($valid_users);$user = (!empty($_SERVER['PHP_AUTH_USER'])) ? $_SERVER['PHP_AUTH_USER'] : '';$pass = (!empty($_SERVER['PHP_AUTH_PW'])) ? $_SERVER['PHP_AUTH_PW'] : '';if (!((in_array($user, $valid_usernames)) && ($pass == $valid_users[$user]))) {header('WWW-Authenticate: Basic realm="Private Site"');header('HTTP/1.0 401 Unauthorized');die('Not authorized.');}}}Then, you can leverage it wherever you’d like. For example, on an Acquia site I might add this to the bottom of settings.php:
12345678910if (!empty($_ENV['AH_SITE_ENVIRONMENT'])) {switch ($_ENV['AH_SITE_ENVIRONMENT']) {case 'dev':lock_with_basicauth(['agileadam' => 'mysecretdevpass']);break;case 'test':lock_with_basicauth(['agileadam' => 'mysecretstagepass']);break;}}For non-Acquia sites I’d call the function at the bottom of settings.local.php.
-
Drupal 8 User Photo Update Form
Recently I had to come up with a simple way for users to change their member profile photo without requiring them to visit the user edit screen. Here’s the result:
First, I added a new Image field called “Member Photo” to the user account fields (machine name field_user_picture). Here are the settings I used:
- Allowed extensions: png, gif, jpg, jpeg
- File directory: users/[date:custom:Y]-[date:custom:m]
- Max size: 10 MB
- Checked: Enable alt field
- Checked: Alt field required