1

in Drupal 8, I try to create a form with a checkboxes field.

public function buildForm(array $form, FormStateInterface $form_state) {
      $config = $this->config('communication_annuaire.settings');
      $form['fields_to export_to_annuaire'] = array(
       '#title' => $this->t('Fields to export to annuaire'),
       '#type' => 'checkboxes',
       '#options' => $this->getFieldOptions(),
       '#default_value' => $config->get('fields_to export_to_annuaire'),
    );

    return parent::buildForm($form, $form_state);
}


public function submitForm(array &$form, FormStateInterface $form_state) {
      parent::submitForm($form, $form_state);
      \Drupal::configFactory()
         ->getEditable('communication_annuaire.settings')
    // Set the submitted configuration setting
     ->set('fields_to export_to_annuaire', $form_state->getValue('fields_to export_to_annuaire'))
    ->save();
}

public function getFieldOptions() {
    $fields = array();
    foreach (\Drupal::entityManager()->getFieldDefinitions('node', 'structure') as $field_name => $field_definition) {
       if (!empty($field_definition->getTargetBundle())) {
         $fields[$field_name] = $field_definition->getLabel();
       }
     }
    return $fields;
}

The problem is that even if I check one or several checkboxes, data for the field is always empty in submitForm function: Array( [body] => 0 [field_contact] => 0 [field_infos] => 0 [field_logo] => 0 [field_site] => 0 [field_structure] => 0)

I tried with array_filter($form_state->getValue('fields_to export_to_annuaire')), but it is not better.

How can I solve this problem ?

Thanks

  • The problem was a space in the id of the field. I wrote fields_to export_to_annuaire instead of fields_to_export_to_annuaire – Lucuhb Mar 20 '18 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.