Style checkbox as switch

I want to style a checkbox as a switch, but I don’t know how to achieve this.

I’m using bootstrap 4.6.2 and TWBS. I thought something like this would do the trick but it doesn’t.

        $this->add([
            'type' => Checkbox::class,
            'name' => 'test',
            'options' => [
                'label' => 'netto/brutto',
                'switch' => true,
            ],
        ]);

What am I missing?

Hi @oliver681,
You can knock yourself out trying out the documentation here and drink wine at your own expense. Take care!

Hey there,

the first question must be: Do you want to rely on an additional dependency like Bootstrap or something else, or do you want to archieve your own solution?

Edit: Okay, it 's early and I 'm not yet done with my first coffee. Haven 't read that you already use Bootstrap and TWBS. So my question is obsolete. Just ignore it. :wink:

Haha, no problem :smiley:

In case I don’t find a solution, I will “hardcode” the corresponding html in the phtml file. But that would break a bit the use of the form view helper.

Yes, I saw it, but isn’t that exactly what I did using the ‘switch’ => true option?

If switch true was the only option which could work they would have shared it in the doc. They’ve other options too. I’ve not used it and I don’t only switch option true is needed then why they didn’t show with the option true case? I would say stick with the docs as it or build your own. Also, you’re using BS 4, not 5. Sir 681.

switch is an attribute of the checkbox element, so

$this->add([
    'type' => Checkbox::class,
    'attributes' => [
        'switch' => true,
    ],
]);

If the markup doesn’t end up looking like <input type="checkbox" switch name="foo">, then the switch attribute is not supported by Laminas form - Open an issue or a PR to add it.

If you don’t see native browser switch styling, then it’s not supported by your browser. From what I know, Safari has native styling but I’m unsure about other browsers.

I wanted to use a number of Bootstrap elements in my forms, and display them using formCollection. I opted for custom elements an view helpers. That way if I wanted a switch I would just use bsSwitchCheckbox, or alias that to Checkbox to changed all elements.

Just to ask the obvious. Is TWBS in general working? Because I thought as well that I am doing something wrong till I realized that TWBS is not activated at all.

1 Like