Form select: Dynamic #default_value vs. caching

Hi All,

I’m creating a simple module where the user can change his region via a dropdown on top of the screen with an auto postback.

The choice get stored in a cookie, so when the user returns, he doesn’t have to make that choice again. So when the cookie exists the default_value of the dropdown is the value of that cookie.

When developing everything worked well, but when I moved to stage environment and testers started browsing anonymous, it seemed that the default_value got cached. The value of the cookie changes, but the selected value remains.

I even tried a cache context for that cookie, but that doesn’t seem to work…

Here’s my code:


class RegioKeuzeDropdownForm implements FormInterface{
    function getFormId(){
        return 'regio_logica_regiokeuzedropdown_form';
    function buildForm(array $form, FormStateInterface $form_state){
        //Dummy value for Bots
        $regio_user = '300';
            $regio_user = $_COOKIE['RegioCookie'];
        $form['regio_select'] = array(
            '#type' => 'select',
            '#title' => 'Jouw regio: ',
            '#options' => array(
                '304' => 'Antwerpen',
                '306' => 'Vlaams-Brabant',
                '309' => 'West-Vlaanderen',
                '311' => 'Oost-Vlaanderen',
                '322' => 'Limburg',
            '#default_value' => $regio_user,            
            '#attributes' => array('onChange' => 'document.getElementById("regio-logica-regiokeuzedropdown-form").submit();'),            
        //Submit is required, but hidden by style attribute
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            '#attributes' => array('style' => 'display: none;'),
        return $form;
    function validateForm(array &$form, FormStateInterface $form_state){       
    function submitForm(array &$form, FormStateInterface $form_state){
        $value = $form_state->getValue('regio_select');
        setcookie("RegioCookie", $value, time()+(3600*24*24),"/");                                


* Provides a 'Regiokeuze' Block
* @Block(
* id = "regio_block",
* admin_label = "Regiokeuze block"
* )
class RegioKeuzeBlock extends BlockBase implements BlockPluginInterface {    
    * {@inheritdoc}
    public function build() {
        $form = Drupal::formBuilder()->getForm('Drupalregio_logicaFormRegioKeuzeDropdownForm');
        return array(            
            "#markup" => render($form),
            "#cache" => array("contexts" => array('cookies:RegioCookie')),

Does anyone knows how to solve this problem? Any help would be much appreciated.

Kind regards,

Drupal version: