Create and Render link in drupal_set_message | Drupal 8

Create and Render link in drupal_set_message

Submitted by editor on Tue, 12/22/2015 - 15:29
Question

How to create /  render html link in drupal_set_message() with Drupal 8 ?

Example : Password Reset Link.
      $link = \Drupal::l(t('Link'), \Drupal\Core\Url::fromRoute('user.pass'));
      drupal_set_message(t("Password Reset Link : @link!", ['@link!' => $link]));

 

In a form, You can use it like:

$form['a_link'] = [
'#type' => 'markup',
'#markup' => t('Password Reset Link : @link', array('@link' => $link)),
];

The l() function \Drupal::l() is deprecated.

Use \Drupal\Core\Link instead
Example:
use \Drupal\Core\Link;
$link = Link::fromTextAndUrl($text, $url);
#OR
$link = \Drupal\Core\Link::fromTextAndUrl($text, $url);

Add Link to drupal_set_message (Examples)

use Drupal\Core\Link;
use Drupal\Core\StringTranslation\TranslatableMarkup;

$link = Link::createFromRoute('Link title (User Login)', 'user.login')
->toString();
$text = new TranslatableMarkup("The link is : @link)", ["@link" => $link]);
drupal_set_message($text, 'ok');

Get HTML (generated) Link
$link_html = Link::createFromRoute('Link title (User Login)', 'user.login')
->toString()
->getGeneratedLink();
kint($link_html);

 

Tags

Comments

Add new comment