1

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 selects 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.

2
  • 1
    It has changed a bit since D7 (this method also wouldn't have worked for D7 BTW, it's a bit more convoluted). There's a good example here that should help; put simply, it's the form builder that deals with setting values, not a render function, and with your current code the form doesn't contain the selects as elements (they're just being passed as an argument to the table's render callback), so values aren't set
    – Clive
    May 23 '16 at 17:10
  • @Clive Thank you for the link! It definitely set me going in the right direction, and now I've got it working.
    – Greenstack
    May 23 '16 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.