Developer Guide
Adding a Key Select element to a form
Key adds a Form API element called key_select that behaves like a select element, but that is populated with available keys as options. This allows module developers to easily add a key field to a settings form, like this:
$form['secret_key'] = [
'#type' => 'key_select',
'#title' => $this->t('Secret key'),
];
There are a couple of additional properties that can be used:
#key_filters
An array of filters to apply to the list of keys. Filtering can be performed on any combination of key provider, key type, and key type group. Examples:#key_filters = ['type' => 'mailchimp']
This would only display MailChimp keys.#key_filters = ['provider' => 'file']
This would only display keys that use the File key provider.#key_filters = ['type' => 'mailchimp', 'provider' => 'file']
This would only display MailChimp keys that use the File key provider.#key_filters = ['type_group' => 'encryption']
This would only display encryption keys.
-
#key_description
This is a boolean value that determines if information about keys is added to the element's description. It isTRUE
by default and it prepends the description with the following text (with a link to the add key form):Choose an available key. If the desired key is not listed, create a new key.
This can be disabled by setting
#key_description
toFALSE
. -
#empty_value
The value of the option that is used to denote no selection. -
#empty_option
The label that will be displayed to denote no selection.
Using a Key in Drupal 8
Modules can retrieve information about keys or a specific key value by making a call to the Key Manager service. It is best practice to inject the service into your own service, form, or controller. The following examples assume the use of the \Drupal
object for brevity, but the examples can be extrapolated to fit the use case of your module.
Get all key entities
Drupal::service('key.repository')->getKeys()
Get a single key entity
Drupal::service('key.repository')->getKey($key_id)
Get a key value
Drupal::service('key.repository')->getKey($key_id)->getKeyValue()
Get a key value as an associative array
(for multivalue keys)
Drupal::service('key.repository')->getKey($key_id)->getKeyValues()
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion