1

I am populating data from database to radio button and want to check the first value as default but I have no idea on how to do it. Here is my coding that I've done so far.

View

<?php if($designThemes != null){;  ?>

<?php foreach ($designThemes as $designTheme) { ?>

<?php
$designThemesValue = (set_value('theme_name') ? set_value('theme_name') : $designTheme['slug_url']);
$designThemesAttr = array(
    'name'  => 'designThemes',
    'value' => $designThemesValue,
);
?>
<div class="col-md-4 col-sm-4">
    <div class="radio custom-radio">
        <label>
            <?php echo form_radio($designThemesAttr); ?>
            <span class="fa fa-circle"></span> <?php echo $designTheme['theme_name'] ?>
        </label>
    </div>
</div>
<?php }}; ?>

If I add 'checked' => TRUE in $designThemesAttr = array() the system will check the last value of radio button as the default, but I wanted to check the first value.

Emerald
  • 864
  • 1
  • 14
  • 37
  • _"If I add 'checked' => TRUE in $designThemesAttr = array() the system will check the last value of radio button as the default, but I wanted to check the first value."_ - of course, because you would be setting that for _every_ radio button - you need to do it only for the first one, so your question boils down to how to figure out whether you are in the first iteration of a foreach loop, so ... https://www.google.com/search?q=foreach+loop+check+if+first+iteration – CBroe Jun 14 '17 at 09:23
  • First hit from that search - https://stackoverflow.com/questions/1070244/how-to-determine-the-first-and-last-iteration-in-a-foreach-loop – TimP Jun 14 '17 at 09:28

2 Answers2

2

solved your issue you can set it by conditional statement as replace your code by this

   <?php if($designThemes != null){;  ?>

<?php $i=1;foreach ($designThemes as $designTheme) { ?>

<?php
$designThemesValue = (set_value('theme_name') ? set_value('theme_name') : $designTheme['slug_url']);
$designThemesAttr = array(
    'name'  => 'designThemes',
    'value' => $designThemesValue,
);
if($i==1){
    $designThemesAttr['checked'] = TRUE;
}
?>
<div class="col-md-4 col-sm-4">
    <div class="radio custom-radio">
        <label>
            <?php echo form_radio($designThemesAttr); ?>
            <span class="fa fa-circle"></span> <?php echo $designTheme['theme_name'] ?>
        </label>
    </div>
</div>
<?php $i++; }}; ?>
Niraj patel
  • 525
  • 4
  • 12
0

'checked' => TRUE in $designThemesAttr = array() the system will check the last value of radio button as the default. This is right, because you doing it inside a for loop, and only one radio remains selected inside a group. So the last one is showing checked.

So maintain a variable to count the iteration like:

$count = 1;

if( $count = 1; )
{
   // use 'checked' => TRUE here
   $count++;  // The value is incremented so that the if condition can't run again. This will add 'checked' => TRUE to first radio only.
}
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59