Toggle boolean true/false

How do I get a boolean value from the Toggle Element?

Default is a String “true” or “false”.

You mean like this?..

<?php if($page->yourtogglefield()->bool()): ?>
  <!-- stuff that happens if its true -->
<?php endif ?>
1 Like

Thanks. Thats it!

What’s the equivalent of this being false?

Bool() returns a boolean, eithertrue or false. But in an if-statement like above, the action is only executed if bool() returns true.

To do something if bool() returns false:

<?php if ($page->yourtogglefield()->bool() === false) : ?>
  <!-- stuff that happens if `false` is returned -->
<?php endif ?>

So

<?php if ($page->yourtogglefield()->bool()) : ?>
  <!-- stuff that happens if its true -->
<?php endif ?>

is short for

<?php if ($page->yourtogglefield()->bool() === true) : ?>
  <!-- stuff that happens if its true -->
<?php endif ?>
2 Likes

Is this fine too?

<?php if (!$page->yourtogglefield()->bool()) : ?>
  <!-- stuff that happens if `false` is returned -->
<?php endif ?>

Sorry for my noob questions :slight_smile:

I was also searching the reference for the “bool” field method. Is there a reason why this doesn’t appear in the docs?

I would look at https://getkirby.com/docs/reference/templates/field-methods/to-bool

But thats the “toBool” Method, as I can see it’s totally different as the “bool” method right?

1 Like

bool() is an alias for toBool(). The following aliases exist for field methods:

    // Field method aliases
        Field::$aliases = [
            'bool'    => 'toBool',
            'esc'     => 'escape',
            'excerpt' => 'toExcerpt',
            'float'   => 'toFloat',
            'h'       => 'html',
            'int'     => 'toInt',
            'kt'      => 'kirbytext',
            'kti'     => 'kirbytextinline',
            'link'    => 'toLink',
            'md'      => 'markdown',
            'sp'      => 'smartypants',
            'v'       => 'isValid',
            'x'       => 'xml'
        ];
2 Likes

Yes, you can use that too, the more explicit code is maybe easier to understand at first look, though.

1 Like