Search code examples
sapui5

How to validate and scroll to sap.m.RadioButtonGroup


The task is straight forward:
The user has to select an entry in a group of radio buttons, otherwise the validation should fail.
RadioButtonGroup
In order to be nice to the user, I'd also like to scroll to that RadioButtonGroup when its validation fails since it's further down and may not be in sight (as in my example linked below).

The implementation is not so straight forward to me because RadioButtonGroup does not have the property required.
Here's my code example - the RadioButtonGroup is in file SomeView.view.xml at line 420...
I have not really tried anything so far because I have no idea what to try.

Does anyone know if this is possible without compromising the existing validator implementation (that I got from here)?


Solution

  • The implementation is not so straight forward to me because RadioButtonGroup does not have the property required.

    Only sap.m.Label needs the property required="true". Not the control sap.m.RadioButtonGroup itself.

    The control sap.m.RadioButtonGroup has a property called selectedIndex. In your Code-Snippet you set the property selectedIndex="-1". If the user selects an sap.m.Radiobutton the selectedIndex will change to 0..3. Let's capture that with sap.ui.model.type.Integer.

     // JSON dummy data
                var oData = {
                    text   : "Test",
                    userEmail : "[email protected]",
                    number : 50,
                    date   : "01.01.2021",
                    selectedIndex: -1
                };
    
     <Label text="Final answer?" required="true"/>
                <RadioButtonGroup 
                   id="answer" 
                   columns="4" 
                   selectedIndex="{ path: '/selectedIndex',
                   type: 'sap.ui.model.type.Integer',
                   constraints : { 
                                  minimum : 0, 
                                  maximum : 3 
                                 }}">
                    <RadioButton id="A1" text="A"/>
                    <RadioButton id="B1" text="B"/>
                    <RadioButton id="C1" text="C"/>
                    <RadioButton id="D1" text="D"/>
                </RadioButtonGroup>
    

    The Validator.js only checks for following properties

     aValidateProperties   = ["value", "selectedKey", "text"] 
    

    so we add the propertie selectedIndex

    aValidateProperties   = ["value", "selectedKey", "text", "selectedIndex"]
    

    Validation works now ! Code-Example

    In order to be nice to the user, I'd also like to scroll to that RadioButtonGroup when its validation fails since it's further down and may not be in sight (as in my example linked below).

    See this offical Example