I have a select drop down. When the user selects a value from the drop down, the user will then click on a button and based on what the user has selected it will open a url in a new tab. While this is quite simple in JavaScript I am struggling how to figure this out in drupal.

So far I have created a custom module which has a select form and the submit button. From here I am stuck as to how to write if user has selected value a open google.com etc. any suggestions or pointers would be greatly appreciated.


You can do this by using $form_state->setResponse() together with TrustedRedirectResponse.

Create the dropdown, like this:

$form['select'] = [
  '#type' = 'select',
  '#title' => t('Select'),
  '#options' = [
    'https://google.com' => t('Google'),
    // More links...

To open the link in a new tab, you can add this to your form:

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

Then create the submit handler, like this:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->setResponse(new TrustedRedirectResponse($form_state->getValue('select'), 302));
  // You can change the response code from 302 to whatever you need
| improve this answer | |
  • 2
    Wow! Form attributes target blank and it opens a new tab on submit? Nice one 👍🏼 – leymannx Nov 26 '19 at 16:19
  • 2
    @leymannx Thank you! It got the idea from this post, stackoverflow.com/questions/5709590/submit-a-form-in-a-new-tab. – user72672 Nov 26 '19 at 16:28
  • Awesome thank you! – lolname101 Nov 26 '19 at 23:56
  • @lolname101 If my answer helped you, please accept it, thanks :) – user72672 Dec 20 '19 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.