jeudi 2 décembre 2021

Storing Drupal Form Checkboxes in a Database

Working on a form that will have 25 checkboxes in a checkboxes set. I need to store the checked keys in a database, and be able to restore the Edit form to it's checked state. I do have a solution, but it just seems odd. This is my first effort at a form and am looking for a best practice on how to solve this problem.

A prototype of my checkboxes set:


$form['medical'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Medical Conditions you currently or have previously suffered.'),
      '#options' => [
        'Asthma' => $this->t('Asthma'),
        'Anxiety' => $this->t('Anxiety'),
        'Diabetes' => $this->t('Diabetes'),
        'Schizophrenia' => $this->t('Schizophrenia'),
        'Low Blood Sugar' => $this->t('Low Blood Sugar'),
        'High Blood Pressure' => $this->t('High Blood Pressure'),
        'Stroke' => $this->t('Stroke'),
        'HIV' => $this->t('HIV'),
        'IBS' => $this->t('IBS'),
      ],
      '#default_value' => $savedArray,

I get the checked keys using

$medical = $form_state->getValue('medical');
$chked = implode(',', $medical);

This gives me a comma separated string, something like something like 'Asthma,Diabetes,Low Blood Sugar,Stroke,IBS,0,0,0,0'.

I get the portion before the first ',0', the first unchecked checkbox and save that to the database.

$chked = substr($chked, 0, strpos($val, ',0'));

So the database is storing a comma separated list of Key values that represent the checked boxes.

To restore the state of the form, I get that string value from the database and explode it into an array, and use that array as the #default_value of the checkbox set.

 $savedArray = explode(',', $chked)
 #default_value => $savedArray

This all works, but it just seems pretty weird. I am new to Drupal and php. Is this an reasonable solution? Is there some built in functionality that manages this? This feels a lot like Jr programmer hackery to me!




Aucun commentaire:

Enregistrer un commentaire