Created
November 19, 2021 13:47
-
-
Save levmyshkin/ac6eeac952465304dde606707f036c92 to your computer and use it in GitHub Desktop.
Drupal hook_form_alter() add submit and validate for existing form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implements hook_form_alter(). | |
*/ | |
function drupalbook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) { | |
if ($form_id == 'drupalbook_admin_settings') { | |
$form['drupalbook_api_key']['#attributes']['placeholder'] = 'API key'; | |
$form['drupalbook_api_client_id']['#attributes']['placeholder'] = 'API client ID'; | |
$form['#validate'][] = 'drupalbook_settings_validate'; | |
$form['#submit'][] = 'drupalbook_settings_submit'; | |
} | |
} | |
/** | |
* Custom validation callback. | |
*/ | |
function drupalbook_settings_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) { | |
if (strpos($form_state->getValue('drupalbook_api_key'), 'google') === FALSE) { | |
$form_state->setErrorByName('drupalbook_api_key', t('API Key must start from "google".')); | |
} | |
} | |
/** | |
* Custom submit callback. | |
*/ | |
function drupalbook_settings_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) { | |
// drupal_set_message is deprecated | |
// drupal_set_message(t('An error occurred and processing did not complete.')); | |
\Drupal::messenger()->addStatus( | |
t(htmlentities('Insert API key in your <head> tag: <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" type="text/javascript"></script>.')) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment