Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By Gábor Hojtsy on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.x
Issue links:
Description:
The EntityInterface got the following methods, that can now be used on entities inheriting from this interface:
- language() - returns the default language of a language-specific entity.
- translations() - returns the languages the entity is translated to.
- get() - to retrieve property or field values in a specific language, no need to fiddle in the field arrays on entities anymore!
- set() - to update property or field values in a specific language, no need to fiddle in the field arrays on entities anymore!
The basic usage for the new accessors is pretty straightforward:
<?php
// Change a field value.
$body = $comment->get('comment_body');
$body[0]['value'] = 'This is actually a perverted tango';
$comment->set('comment_body', $body);
// A plain property is handled the same way.
$created = $comment->get('created');
if ($created > REQUEST_TIME) {
watchdog('warning', 'Ahead of their times');
}
?>
Also language-aware access has been greatly simplified:
// Retrieve a translation:
$german_body = $comment->get('comment_body', 'de');
// Set a translation:
$german_body[0]['value'] = 'updated';
$comment->set('comment_body', $german_body, 'de');
The following example just updates all translations:
// Retrieve the comment body in the original language. No need to specify one
// here as the default is the original language.
$original = $comment->get('comment_body');
// Loop over the comment translations and provide a comment body value for
// each one.
foreach ($comment->translations() as $langcode => $language) {
// We want to provide a value only for translations, hence we skip the
// original language.
if ($langcode != $comment->language()->langcode) {
$body = array();
$t_args = array('@language' => $language->name, '%original' => $original[0]['value']);
$body[0]['value'] = t('This is the @language translation of %original', $t_args, array('langcode' => $langcode));
// Here we need to specify the property language the passed value must be
// assigned.
$comment->set('comment_body', $body, $langcode);
}
}
Impacts:
Module developers