Skip to main content

Drupal 8: How to add HTML markup on link (in a form or anywhere else)

This is a snippet for using a link button with drupal form api.

use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Render\Markup;

//inside buildFormClass i want to show a back button with a fontawesome icon (left angle)
public function buildForm(array $form, FormStateInterface $form_state,$arg = NULL) {
 . . . . .
    $linkText = '<span class="fa fa-angle-left"></span>'. $this->t('Back');
    $form['actions']['previous'] = [
      '#type' => 'link',
      '#title' => Markup::create($linkText),
      '#attributes' => [
        'id' => 'goto-step-three',
        'class' => [
          'btn',
          'btn-green',
          'btn--goback-step-one',
        ],
        'data-twig-id' => 'goto-step-one',
      ],
      '#weight' => 0,
      '#url' => Url::fromRoute('website_booking.multistep_one',['nid' =>  $this->store->get('poi_nid')]),
    ];
}

in a controller or somewhere else


$url = Url::fromUri('https://.pixelthis.gr');     
$linkText = '<span class="fa fa-angle-left"></span> '.$this->t('Go Back');
$linkHTMLMarkup = Markup::create($linkText);
$link = Link::fromTextAndUrl($linkHTMLMarkup, $url);
$link = $link->toRenderable();

 

form api hook_form_alter