How do I define checkboxes in a form?

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?


  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.

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'),

Category: forms Time: 2016-07-28 Views: 0
Tags: database forms

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 1.092 (s). 13 q(s)