I want to create a custom enum type for the custom control like https://sapui5.hana.ondemand.com/docs/api/symbols/sap.ui.core.ValueState.html#.Error.
My questions are:
Here is an example: https://embed.plnkr.co/DhtkXOkMi12D1AYK
In order to create an enum type in UI5, there are certain rules to take into account:
sap/base/util/isPlainObject
.{
"Red": "Red",
"Blue": "Blue",
"Yellow": "Yellow"
}
In order to actually make use of the enum object:
The enum object must be registered with sap/ui/base/DataType.registerEnum
* since UI5 1.120. For example:
/**
* In control/type/Color.js"
* Root namespace: "my.demo"
*/
sap.ui.define([
"sap/ui/base/DataType",
], (DataType) => {
"use strict";
const color = {
Red: "Red",
Blue: "Blue",
Yellow: "Yellow",
};
DataType.registerEnum("my.demo.control.type.Color", color); // since 1.120
return Object.freeze(color);
}/*, true*//*no longer needed since UI5 1.120 thx to registerEnum*/);
// Exporting globally (true) is required until 1.119.
The module name of the object must be assigned to the type
in the property metadata:
// in control/Square.js
sap.ui.define([
"sap/ui/core/Control",
"./type/Color", // require the module to register the enum
"...",
], function(Control) {
"use strict";
return Control.extend("my.demo.control.Square", {
metadata: {
properties: {
"selectedColor": {
type: "my.demo.control.type.Color", // <-- name of the enum
bindable: true,
},
},
},
// ...
});
});
In my example above, it's the selectedColor
property that awaits only "Red"
, "Blue"
, or "Yellow"
. Let's test it:
new Square().getMetadata().getProperty("selectedColor").getType().isEnumType()
returns true
. ✔️new Square().setSelectedColor("Hans")
throws an error as expected:
"Hans" is of type string, expected my.demo.control.type.Color for property "selectedColor" of Element [...]. ✔️
new Square().setSelectedColor("Yellow")
successfully stores the value. ✔️Do not try creating an enum type via DataType.create
.
Array types and enumeration types cannot be created with this method. They're created on-the-fly by
DataType.getType
when such a type is looked up. (Source)
* For UI5 1.119 or lower, refer to the previous answer.