How to Add target attribute to form and submit buttons in Drupal 8 / 9

5
(1)

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;
});

Similar Posts:

1,513

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Scroll to Top