Search code examples
javascriptsapui5

How to reset controls to their initial values in SAPUI5?


I have a form with a lot of controls (ComboBoxes, TextAreas, RadioButtons) using OpenUI5. I give the values of the controls on the server side in C++. What I want is to have a reset button, which will clear the choices of the user and revert the controls back with the default choices. Until now, I am able to have the form and the controls as an JS object like this:

this.byId("MainForm").getModel();

The only think I am able to do until now is to totally clear all the controls like this:

this.byId("MainForm").getModel().setData(null);

For example I have a ComboBox and the default value from my model is the second choice. How can I keep this value and set it back to the control?


Solution

  • Use the API of the respective control. sap.m.ComboBox features the method setSelectedKey(sKey). sap.m.TextArea features the method setValue(sValue). sap.m.RadioButton features the method setSelected(bSelected).

    Bind a press event to your reset button. in your press event get the form's controls. then reset the form's controls to their initial states with their respective methods.

    <!-- in your e.g. xml view -->
    <Button type="Reject" text="Reset" press="onPressResetButton"></Button>
    
    // in your js controller
    onPressResetButton: function() {
      ...
      var oComboBox = this.byId("your-combo-box-id");
      oComboBox.setSelectedKey("your-initial-item-key");
      ...
    }
    

    Get the initial values for the form's controls from your backend or keep them in a local model in the frontend.