I'm working on a migration project. I have a form in a custom module that creates a series of checkboxes for URLs to scrape. The form logic looks like this:
foreach ( \Drupal\scrape\Api\Scraper::loadUrls() as $index => $url ) {
$form['url_' . $index] = [
'#type' => 'checkbox',
'#title' => $url . ' — ' . \Drupal::l('(link)', Url::fromUri($url)),
'#return_value' => $url,
];
}
This code does what I want it to do, but all the checkboxes default to 'unchecked'.
'url_0' => integer0
'url_1' => string(27) "https://myurl1.com"
'url_2' => integer0
I want these checkboxes to default to checked. I couldn't find documentation on how to do it in Drupal 8, so I tried several things, and finally hit upon '#checked' => TRUE,
(or any value that evaluates truthily). Now the checkboxes are defaulting to checked.
However, even though I have #return_value
specified, the value returned in the form submission is now TRUE
(from kint):
'url_0' => boolTRUE
'url_1' => boolTRUE
'url_2' => boolTRUE
Since any truthy value defaults the checkbox to checked, I tried '#value' => $url,
but then upon submission, the values don't indicate their checked status:
'url_0' => string(86) "https://myurl0.com"
'url_1' => string(27) "https://myurl1.com"
'url_2' => string(29) "https://myurl2.com"
I guess my final option is to have a separate, hidden value for each URL, and map checkbox values to see if the user wants that URL included.
Is there a way I can default my checkboxes to TRUE, while maintaining their #return_value
?