0

I am using the following code for Drupal 6.

 foreach (variable_get('cleanupeditform_formkeys', 0) as $key => $value ) {     
    $form['cleanupedit_hide'][CLEANUPEDITFORM_HIDEPREFIX . $key] = array(      
      '#type' => 'checkbox',    
      '#title' => t('Hide ') . $value,    
      '#default_value' => 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 &$form, FormStateInterface $form_state) {
     foreach ((\Drupal::state()->get('cleanupeditform_formkeys') ?: 0) as $key => $value ) {
       parent::submitForm($form,$form_state);
       $this->config('cleanupeditform.admin_settings')
         ->set('element', $form_state['cleanupedit_hide'][CLEANUPEDITFORM_HIDEPREFIX . $key])
         ->set('element', $form_state['cleanupedit_allow'][CLEANUPEDITFORM_ALLOWPREFIX . $key])
         ->save();
     }
     parent::submitForm($form, $form_state);
  }

Please help me to find out a solution.

1 Answer 1

1

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()->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 &$form, FormStateInterface $form_state) {
  foreach ((\Drupal::state()->get('cleanupeditform_formkeys') ?: []) as $key => $value ) {
    $this->config('cleanupeditform.admin_settings')
      ->set(CLEANUPEDITFORM_HIDEPREFIX . $key, $form_state->getValue(CLEANUPEDITFORM_HIDEPREFIX . $key))
      ->set(CLEANUPEDITFORM_ALLOWPREFIX . $key, $form_state->getValue(CLEANUPEDITFORM_ALLOWPREFIX . $key))
      ->save();
  }
  parent::submitForm($form, $form_state);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.