Toggle css with radio button

Hi Everyone,

I’m super new to PHP and I’m just getting started with Kirby and trying things out.

I’m making a simple gallery using a list of images. I want to be able to toggle the css class of an image from the panel. My code is below but it’s not working, any help?

<div class="gallery col-md-12">
                <?php foreach ($page->images() as $image): ?>
                    <li class="<?php 
                    if ( $image->radiofield()->bool()): 
                        $class = 'col-md-6';
                    } else {
                        $class = 'col-md-12';
                        <?= $image ?>
                <?php endforeach ?>

Hi there, welcome to the forum :slight_smile:

You should be able to do this with the e() helper.

<li class="<?php e($image->radiofield()->bool() === true, 'col-md-6', 'col-md-12') ?>">

Or the long way round:

if ($image->radiofield()->bool() === true) {
    $class = 'col-md-6'
} else {
    $class = 'col-md-12'

<li class="<?= $class ?>">

On a side note, its generally bad practice to put PHP inside an HTML attribute like that, it is much more readable to do it above and echo the result into the attribute.

1 Like

On a side note: The reason why your code does not work is that while you correctly define the $class method with the desired value, you then do nothing with this variable.

I couldn’t get this to work but as I’m only switching between two classes I used the same logic I used a toggle and got it to work. If I had multiple radio options for multiple classes how would each radio trigger a different class?

Then your radio option would hold the class name:

    type: radio
      "col-md-3": 4 columns
      "col-md-4": 3 columns
      "col-md-6": 2 columns

The only output the value:

<?php echo $page->radiofield()->html() ?>

Checking for bool doesn’t make sense for multiple radio fields. Only for toggle, single checkbox or single radio with appropriate values.