I have a for
loop in my code that creates elements in a table using data from the database. Each row has a select element, where the default option should correspond to what's stored in the database:
$listmode = [
'#type' => 'select',
'#options' => [
'none' => t('Unlisted'),
'black' => t('Blacklist'),
'white' => t('Whitelist'),
],
'#attributes' => ['id' => ''],
'#default_value' => '',
];
$rows = array();
foreach (BlocceConfigStorage::getBlocks() as $block){
//I really wish there were a better way to do this
if ($block->listing == null || $block->listing == 2){
$default = 'none'; //set select to unlisted
}
else if ($block->listing == 0){
$default = 'black'; //set select to blacklist
}
else if ($block->listing == 1){
$default = 'white'; //set select to whitelist
}
$listmode['#default_value'] = $default;
$pre = $listmode;
$pre['#attributes']['id'] = 'select-block-'. $block->id;
$tlist = drupal_render($pre);
$rows[] = [
'data' => [$block->id, $block->info, $tlist]
];
}
I attach the generated rows here:
$form['table'] = array(
'#type' => 'table',
'#header' => $thead,
'#rows' => $rows,
'#attributes' => array(
'id' => 'blocce_blocks',
),
);
I've tried messing around with the sample found here and adding a single listmode
select to the form and setting the default. Both of them worked on their own; I've also tried pre['#default_value'] = $default
, but that also was availed me nothing. I suspect that the problem either lies in the drupal_render($pre);
(without this, however, the select
s refuse to show up) or that the for loop itself is the problem.
Tl;dr: How do I set the default select option in the for loop?
Edit: I'm using Drupal 8, but from what I've seen, this doesn't seem to have changed much from Drupal 7.