processwire / processwire-requests

ProcessWire feature requests.
39 stars 0 forks source link

Documentation request: improve documentation for Select Options #465

Closed teppokoivula closed 4 months ago

teppokoivula commented 1 year ago

The docs page for Select Options doesn't currently seem to explain how one is supposed to check if a specific option is selected within an option field that allows multiple values. Perhaps it's just me, but this seems like a pretty common use case, so I feel it should be covered.

What didn't work

The docs include an example of iterating over selected values, but since that doesn't seem to make much sense in this case, here's what I initially tried β€”Β and for the record I use this fieldtype very rarely, so sorry for the rookie mistake πŸ˜…

if ($page->options_field == 'option_value') {

While that seemed to work at first, it resulted in weird behaviour later. I do realize now that this is covered in the docs ("when you access the title (or other) property from the field, it simply gives you the value for that property from the first item"), but admittedly I spent quite a while trying to figure out how I'd managed to misconfigure the field before spotting this note in the docs.

(I'm only mentioning this because to me it seems like a pretty big gotcha: comparing the value stored in a multi-value Select Options field with singular comparison value may seem to work, while it actually doesn't, so the mistake is easy to miss.)

Solution?

Long story short, this is what I ended up with β€” but since this is not documented, I'm not sure if it's what I'm supposed to do:

if ($page->options_field->hasValue('option_value')) {
    // ...
}

Would be nice if the docs could be extended to cover this use case as well πŸ™‚

ryancramerdesign commented 5 months ago

Thanks @teppokoivula that's a good idea, I have added a new section in the documentation here: https://processwire.com/docs/fields/select-options-fieldtype/#checking-if-an-option-is-selected

teppokoivula commented 4 months ago

Very nice, thanks again πŸ™‚