I've created a module for Drupal8 that checks against values in the user register and set an error if the values do no match with something you have entered in a custom form.
My module has got a form where you add a list of username you don't want the user to take and a custom message to display as an error.
Forms works perfectly, I can store data, edit it etc... It is stored under src/Form/
and settings are under config/install
Now when I'm trying to hook the user register form validate I got an error regarding form_set_error()
:
PHP Fatal error: Call to undefined function form_set_error()
Also I think I'm not using $form_state
in the right way (but it does the job)
Here's the code in my_module.module
:
function my_module_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$form['#validate'][] = 'my_module_user_validate';
}
/**
* Custom validation function.
*/
function my_module_user_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
// get module settings
$config = \Drupal::config('my_module.settings');
// Convert $form_state to an array as it has been passed as object, it looks wrong but I could not find any documentation at the moment
$form_state = get_object_vars($form_state);
$name = $form_state['values']['name']);
$usernames = $config->get('my_modules_usernames');
// Username are inserted in a text area separated by an enter key
$usernames = $usernames != '' ? explode("\r\n", $usernames) : array();
foreach ($usernames as $username) {
if ($username == $name[1]) {
//apparently in Drupal 8 form_set_error does not work anymmore
form_set_error('mail', $config->get('my_module_message'));
}
}
}