Configuration form and submission handler I am using the following code for Drupal 6.

 foreach (variable_get('cleanupeditform_formkeys', 0) as $key =&gt; $value ) {     
    $form['cleanupedit_hide'][CLEANUPEDITFORM_HIDEPREFIX . $key] = array(      
      '#type' =&gt; 'checkbox',    
      '#title' =&gt; t('Hide ') . $value,    
      '#default_value' =&gt; variable_get(CLEANUPEDITFORM_HIDEPREFIX . $key , 1),
    );
  }


I need to convert this code to Drupal 8.

In buildForm() I generate the form. I need to save the checkboxes values, and I am using the following code.

public function submitForm(array &amp;$form, FormStateInterface $form_state) {
     foreach ((\Drupal::state()-&gt;get('cleanupeditform_formkeys') ?: 0) as $key =&gt; $value ) {
       parent::submitForm($form,$form_state);
       $this-&gt;config('cleanupeditform.admin_settings')
         -&gt;set('element', $form_state['cleanupedit_hide'][CLEANUPEDITFORM_HIDEPREFIX . $key])
         -&gt;set('element', $form_state['cleanupedit_allow'][CLEANUPEDITFORM_ALLOWPREFIX . $key])
         -&gt;save();
     }
     parent::submitForm($form, $form_state);
  }


Please help me to find out a solution.
There are the following errors in that code:


You call parent::submitForm($form, $form_state) inside the foreach() loop, when it should be called once, outside the loop
You keep setting element, which means you are only saving a single value
Your code is still accessing the FormStateInterface object as an array, as it was done in Drupal 7


I cannot comment about the \Drupal::state()-&gt;get('cleanupeditform_formkeys') part, except that I would probably inject the service as dependency, but I would rather use the following code.

public function submitForm(array &amp;$form, FormStateInterface $form_state) {
  foreach ((\Drupal::state()-&gt;get('cleanupeditform_formkeys') ?: []) as $key =&gt; $value ) {
    $this-&gt;config('cleanupeditform.admin_settings')
      -&gt;set(CLEANUPEDITFORM_HIDEPREFIX . $key, $form_state-&gt;getValue(CLEANUPEDITFORM_HIDEPREFIX . $key))
      -&gt;set(CLEANUPEDITFORM_ALLOWPREFIX . $key, $form_state-&gt;getValue(CLEANUPEDITFORM_ALLOWPREFIX . $key))
      -&gt;save();
  }
  parent::submitForm($form, $form_state);
}