Score:2

Can't preselect time zone in hook_form_alter

ba flag

I'm writing a custom installation profile/distribution and I want to pre-populate some fields in the 'Configure Site' form (/core/install.php). I have managed to prefill/preselect other fields like (Site name, Site email address and Default country) but cannot preselect the Default time zone field. This is the code I am using:

function mydistribution_form_install_configure_form_alter(&$form, FormStateInterface $form_state) {
  $form['site_information']['site_name']['#default_value'] = 'Dummy Site Name';
  $form['site_information']['site_mail']['#default_value'] = '[email protected]';
  
  $form['regional_settings']['site_default_country']['#default_value'] = 'DE';
  $form['regional_settings']['date_default_timezone']['#default_value'] = 'Europe/Berlin';
}

As you can see in the screenshot, I manage to change the Default country successfully, but not the Default time zone.

The "strange" thing though is that when I inspect the code, I can see that the correct timezone has been selected but the form displays London.

enter image description here

I'm based in the UK so I guess this is how London gets selected.

Does anyone know how to get this fixed? Thank you in advance!

Score:4
cn flag

Drupal adds some JS to detect the timezone (through core/misc/timezone.js). This is interfering with your code, but can be removed easily:

unset($form['regional_settings']['date_default_timezone']['#attributes']);

This removes the timezone-detect class from the <select>, stopping it from being processed by the JS.

consuela avatar
ba flag
Thank you so much Clive! That resolved my issue.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.