1

I have a form where I need to add a checkboxes field. The purpose of this form is to display some values from the database. I would like to display id from my database table as checkbox' value (when "active" = 1) and url as checkbox' labels.

The database table's structure is the following.

id | uid | hash          | url          | active

1  | 1   | myhashstring1 | example_url  | 1
2  | 1   | myhashstring3 | example_url4 | 1
3  | 1   | myhashstring2 | example_url2 | 0

How can I achieve this?

2
  • The whole description a little bit ambiguous. What I understand: you have a form where you want to create checkbox related parameters, which will be probably a custom entity. I don't understand this: "get their labels and values?". You want id as "values" and actice = 1 and url as labels? What do you want to say? What do you mean by values and labels?
    – ssibal
    Commented Jul 28, 2016 at 11:35
  • @ssibal: I edited my question.
    – asrob
    Commented Jul 28, 2016 at 12:32

2 Answers 2

1
  1. Creating an '_form' type entry in the mymodule.routing.yml
  2. Form controller will first always do a database query \Drupal::database()->select('mytable')...
  3. You will need the id, url, and active values.
  4. You need to prepare the "options" array like this: array("id" => "url", ...)
  5. And the default array should contain all the active=1 records.
  6. Create the checkbox field item based on Form API description.
  7. In form submission (submitForm) you save back the results (which elements newly activated / deactivated) to the database.
2

As per Drupal 8 form api you can define checkboxes like below:

$form['high_school']['tests_taken'] = array(
  '#type' => 'checkboxes',
  '#options' => array('SAT' => $this->t('SAT'), 'ACT' => $this->t('ACT')),
  '#title' => $this->t('What standardized tests did you take?'),
  ...
);

In your case you can update above code

$options = array();
$options[1] = 'example_url';
$options[2] = 'example_url4';
$options[3] = 'example_url2';

$form['items_selected'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#title' => $this->t('Title you want to give'),
  ...
);

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.