0

With Drupal 8, I have a form with two selects, both filled. I want to add a button/link after each of these two selects, looking like this.

[__SELECT__v][BUTTON]
[__SELECT__v][BUTTON]

The buttons, however, don't have a fixed link because the link target depends on what is selected in the select. Also, the link needs to open a new tab.

For example, if in the select "car1" the key "12345" is selected, the link should open /cars/12345; if "car2" is selected with the key "67890" then "/cars/67890"

This is the code I am using.

$form['select_g1'] = array(
                    '#type' => 'select',
                    '#prefix' => '<div class="container-inline">',
                    '#title' => t('Select &emsp; &emsp; &emsp;&emsp;'),
                    '#options' => $contarray,
                    '#empty_value' => '',
                    '#default_value' => ($ext) ? $row['model'] : "",
                    );
$form['button'] = array(
                    '#markup' => ' <a target="_blank" href=""><span class="button js-form-submit form-submit"><img src="/sites/default/buttons/edit.png"></span></a></div>',              
                    );

Can someone help me there?

2

This is easy to do with javascript.

You can do an onchange event for your select that updates the link,

or you can do a mousedown event on your link that grabs the value from the select.

A quick google search shows many possibilities:

https://stackoverflow.com/questions/11758659/compose-a-link-based-in-selects-option-value

https://stackoverflow.com/questions/20357075/how-to-update-append-to-it-an-href-based-on-dropdown-selection

To add javascript to your form, you need to add the js to your custom module, say in mymodule/js/updatelink.js

then add a mymodule.libraries.yml file in your module

mymodule.updatelink:
  version: VERSION
  js:
    js/updatelink.js: {}
  dependencies:
    - core/jquery
    - core/drupal

then attach it to your form like this:

$form['#attached']['library'][] = 'mymodule/mymodule.updatelink';

You'll want to wrap your code in a Drupal.behaviors class. See https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

|improve this answer|||||
  • Thank you very much! So far it works with including the js and (for testing) displaying a alert when the select changes. – Michael Dec 12 '16 at 14:55

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.