Is there any way to set this in a form_alter? Or should I just validate the checkbox state via JS?
You could replace #required
by setting a custom validation handler in the form alter hook, if you want to generate the error message server-side:
$form_state->setErrorByName('field_tos_accept', $error_message);
When I add '#required_error', this should - in my understanding - throw an error message when the form is submitted.
#required_error'
was introduced in 2011, but when Drupal 8 was released it seems to have stopped working in browsers supporting HTML5 form validation and so it was never really adopted.
However, you can use the HTML5 form attribute novalidate
to disable client-side form validation, then this property works again and you get the custom error message without a custom validation handler:
function themename_form_alter(&$form, &$form_state, $form_id) {
// for entity forms $form_id consists of
// ENTITY_TYPE_BUNDLE_FORM_MODE_form
// BUNDLE only if entity has bundles
// FORM_MODE only if not default
// Examples:
// node_article_edit_form - node edit form for the content type article
// node_page_form - node create form for the content type page
// nodes use for the create form the form mode default
if ($form_id == 'node_nodetype_form') {
$form['#attributes']['novalidate'] = 'novalidate';
$form['field_tos_accept'] = [
'#type' => 'checkbox',
'#title' => t('I agree to the terms of service.'),
'#weight' => '999',
'#required' => TRUE,
'#required_error' => t('Please accept the terms of service.'),
];
}
}
See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-novalidate