Skip to main content
Category:

In this post, I'll show you how to add target attribute to form and submit buttons in Drupal 8.

You have to set the target attribute in the form tag itself:

$form['#attributes']['target'] = '_blank';

To get this functionality to a particular button:

$form['save_and_print'] = array(
  '#type' => 'submit',
  '#value' => t('Save and Print'),
  '#attributes' => array('onclick' => 'this.form.target="_blank";return true;'),
);

To submit the form in same page:

$form['save'] = array(
  '#type' => 'submit',
  '#value' => t('Save'),
  '#attributes' => array('onclick' => 'this.form.target="_self";return true;'),
);

or with jquery:

$('#edit-submit').on('click', function () {
  this.form.target = "_self";
  return true;
});

To submit in a new tab:

$form['save_and_print'] = array(
  '#type' => 'submit',
  '#value' => t('Save and Print'),
  '#attributes' => array('onclick' => 'this.form.target="_blank";return true;'),
);

or with jquery:

$('#edit-print').on('click', function () {
  this.form.target = "_blank";
  return true;
});

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook