I\'m trying to retrieve the URL and the Title values of a Link field in Drupal 8.
In my custom controller, I retrieve the nodes with:<
If you're doing it in a preprocess, I'd suggest to base your code on LinkSeparateFormatter.php. It shows the idea on how to get the title from the link field. Here's a way to do it.
use Drupal\Component\Utility\Unicode;
//...
$field_link = $entity->field_link->first();
$link_url = $field_link->getUrl();
$link_data = $field_link->toArray();
// If you want to truncate the url
$link_title = Unicode::truncate($link_url->toString(), 40, FALSE, TRUE);
if(!empty($link_data['title'])){
// You could truncate here as well
$link_title = $link_data['title'];
}
$variables['content'] = [
'#type' => 'link',
'#url' => $link_url,
'#title' => $link_title,
];