Yii 2 Dropdown List with Boolean Values

So there it is, a big long story about a dropdown list with boolean value. Looking back on it, it was worth the 2 hours, though I wish I would have gotten it sooner. In the end, my instincts proved right. The methods I ended up using are much leaner than trying to write methods with constants. No messy array manipulation either. Just simple one-liners, boom. That’s the way I like it. I hope you like it too.

But as it turns out, I had to rewrite the end of this tutorial. We are never done learning. There is another option when displaying the boolean value in the DetailView::widget:


 ['attribute'=>'is_featured', 'format'=>'boolean'],

The above code goes in your DetailView widget in your view file. When format is specified to boolean, it defaults to yes or no, so once again the architects at Yii 2 have thought of just about everything by giving you a format option out of the box. Well, anyway, now you have more than one choice on how to display the boolean value in the widget. For the DetailView widget, the above format works perfectly, and that’s how I would use it. If you need the value outside of the widget, then the getFaqIsFeaturedName method will come in handy, so the knowledge we gained in how to do it is not wasted.

Anyway, feel free to comment. Links, reviews, and comments are greatly appreciated.

Advertisements

2 thoughts on “Yii 2 Dropdown List with Boolean Values”

  1. Is it possible to create a dropdownlist with a boolean!?
    I’m suffering!

    field($model, ‘bln_reprogramacao’)->DropDownList([1 => ‘Yes’,0 => ‘no’],[‘prompt’=>”])?>

    How can I make it work??

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s