Field trigger event array possibility?

Use case: I have three switches and I only want one to be active.

I tried following in fields.yaml:

image_cover:
        label: Image cover
        span: right
        type: switch
        default: 1
        dependsOn: [image_100]
        trigger:
            action: empty
            field: image_contain
            condition: checked
    image_contain:
        label: Image contain
        span: right
        type: switch
        default: 0
        dependsOn: [image_100]
        trigger:
            action: empty
            field: image_cover
            condition: checked
    image_100:
        label: Image 100%
        span: right
        type: switch
        default: 0
        #dependsOn: [image_contain] # if I un-comment this, of course there is a loop happening
        trigger:
            action: empty
            field: image_cover
            condition: checked

And in my model:

public function filterFields($fields, $context = null)
{
        if ($this->image_100 == 1 && ($fields->image_cover->value == 1 || $fields->image_contain->value == 1)) {
            $fields->image_cover->value = 0;
            $fields->image_contain->value = 0;
        }
}

Now the option when the last switch is on and the second if switched to on doesn’t work.

Of course, I could take a dropdown for this (which I’m going to do now), but I like switches for more oversight.

Question: Would it be possible to implement that the trigger field could be an array?

Possible, but not likely. Multiple triggers are probably better than multiple fields, but the added complexity becomes too high for the returned benefit. Trigger API solves 90% of use cases. This type of thing is best handled with some JavaScript.

If you added a marker to every field…

cssClass: only-one

You could add a JavaScript file to the controller with something like this…

<script>
    // Find all checkboxes
    var allCheckboxes = document.querySelectorAll('.only-one input[type=checkbox]');
    allCheckboxes.forEach(function(el) {
        // Bind to change event
        el.addEventListener('change', function() {
            allCheckboxes.forEach(function(otherEl) {
                // Deselect others except self
                if (el !== otherEl) {
                    otherEl.checked = false;
                }
            });
        });
    });
</script>
1 Like