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

Latest Articles

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file admin_pixelthi… Sun, 12/01/2024 - 16:49 Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

composer
Controlling ckeditor styling options with hook_editor_js_settings_alter admin_pixelthi… Thu, 05/16/2024 - 10:49 Controlling ckeditor styling options with hook_editor_js_settings_alter

Controlling ckeditor styling options with hook_editor_js_settings_alter

php hook hook_editor_js_settings_alter hook_field_widget_single_[WIDGET_TYPE]_form_alter
Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide admin_pixelthi… Tue, 09/05/2023 - 14:18 Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

composer drupal9 drupal10