Skip to Content
Technical Articles
Author's profile photo Suleyman Dogu

Using sap.ui.comp.variants.VariantManagement class to adapt your views with data

Overview

I will explain you in this article how to manage UI5 controls with variant management which you added to an application as shown below and, I’ll show you that what events of Variant Management are and, how to use them.
Before starting, please look into below link to get more information and to see functions and methods about the control.
Some users might want to save and read the values ​​of a page’s layout with variant management control to gain time.

Step 1 : Adding control in View page.

Firstly, you should add Variant Management control in XML view as shown below.

 

Step 2 : Coding of functions of variant control in js.

After coding it in view, we can start using functions of Variant Management control in javascript file.

Firstly you should save layout with key*standard*. So when the page is opened, standard layout will be shown on variant management control first. If you pay attention, default key named ‘standard’ is saved once. The data is saved as empty in this example for standard layout.

 

oCC1: null,
		initSearchVariant: function () {
			var thiz = this;
			var oVM = this.getView().byId("searchFilterVMId");
			var itemName = oVM.data("itemName"); // get item name
			oVM.setModel(new sap.ui.model.json.JSONModel()); // set model
			this.fixVariant(oVM); // fix variant 
			var data = {
				SelectedModuleMain: "",
				SelectedSubModuleMain: ""
			};
			this.setFilterVariant(itemName, "*standard*", null, data, false, function (oCC) { // create item
				thiz.oCC1 = oCC;
				thiz.setVariantList(oCC, oVM); // set variant list
			});
		},
		setFilterVariant: function (itemName, key, text, data, bDefault, callback, fnError) {
			sap.ushell.Container.getService("Personalization").getContainer("com.test").done(function (oCC) {
				if (!oCC.containsItem(itemName)) {
					oCC.setItemValue(itemName, {
						items: []
					});
				}
				var ovar = oCC.getItemValue(itemName);
				if (!ovar.hasOwnProperty("defaultKey")) {
					ovar["defaultKey"] = "*standard*";
				}
				if (bDefault) {
					ovar["defaultKey"] = key;
				}
				if (key != "*standard*") {
					ovar.items.push({
						key: key,
						text: text
					});
				} // if not standard then push into items
				if (data) {
					ovar[key] = JSON.parse(JSON.stringify(data));
				} // if data is available then add data
				oCC.setItemValue(itemName, ovar);
				oCC.save().done(function () {
					if (callback) {
						callback(oCC);
					}
				}).fail(function (err) {
					if (fnError) {
						fnError();
					}
				});
			});
		},
		/* get variant name by key */
		getVariantName: function (oVM, selKey) {
			var aItems = oVM.getVariantItems();
			var selItem = "";
			aItems.forEach(function (item) {
				if (selKey == item.getKey()) {
					selItem = item.getText();
				}
			});
			return selItem;
		},
		/* get variant item by key */
		getVariantByKey: function (oVM, selKey) {
			var aItems = oVM.getVariantItems();
			var selItem = "";
			aItems.forEach(function (item) {
				if (selKey == item.getKey()) {
					selItem = item;
				}
			});
			return selItem;
		},
		fixVariant: function (oVM) {
			oVM.setModel(new sap.ui.model.json.JSONModel()); // set model
			oVM.addVariantItem(new sap.ui.comp.variants.VariantItem({ // set default
				key: "default",
				text: "default"
			}));
			oVM.removeVariantItem(this.getVariantByKey(oVM, "default")); // remove default
		},

		/* set variant list from backend */
		setVariantList: function (oCC, oVM) {
			var itemName = oVM.data("itemName");
			var ovar = oCC.getItemValue(itemName);
			if (ovar.hasOwnProperty("items")) {
				oVM.getModel().setData(ovar.items);
			}
			// set inital default key
			oVM.setInitialSelectionKey(ovar.defaultKey);
			oVM.setDefaultVariantKey(ovar.defaultKey);
			//	this.getOwnerComponent().getModel("filterM").setData(ovar[ovar.defaultKey] === undefined ? "*standard*" : ovar[ovar.defaultKey]);
			this._globalModel.setProperty("/SelectedModuleMain", ovar[ovar.defaultKey]["SelectedModuleMain"]);
			this._globalModel.setProperty("/SelectedSubModuleMain", ovar[ovar.defaultKey]["SelectedSubModuleMain"]);
			//	this.createToken();
		},
		setManageVM: function (oEvent, oCC, itemName, callback) {
			var ovar = oCC.getItemValue(itemName);
			// Rename
			var renameKeys = oEvent.getParameters().renamed;
			if (renameKeys.length > 0) {
				ovar.items.forEach(function (item) {
					renameKeys.forEach(function (reitem) {
						if (reitem.key === item.key) {
							item.text = reitem.name;
							ovar[item.key].text = reitem.name;
						}
					});
				});
			}
			// Delete
			var deletedKeys = oEvent.getParameters().deleted;
			if (deletedKeys.length > 0) {
				for (var i = ovar.items.length - 1; i >= 0; i--) {
					for (var j = 0; j < deletedKeys.length; j++) {
						if (ovar.items[i] && (ovar.items[i].key === deletedKeys[j])) {
							ovar.items.splice(i, 1);
							delete ovar[deletedKeys[j]];
						}
					}
				}
			}
			ovar["defaultKey"] = oEvent.getParameters().def; // Default
			oCC.setItemValue(itemName, ovar);
			oCC.save().done(function () {
				if (callback) {
					callback(oCC);
				}
			}); // save all
		},

		clearValues: function () {
			this._globalModel.setProperty("/SelectedModuleMain", "");
			this._globalModel.setProperty("/SelectedSubModuleMain", "");
		},
		/* on select variant */
		onSelectVariant: function (oEvent) {
			this.clearValues(); // clear previous value
			var oCC = this.oCC1;
			var itemName = oEvent.getSource().data("itemName");
			var ovar = oCC.getItemValue(itemName);
			var selKey = oEvent.getParameters().key;
			var data = ovar[selKey];
			this._globalModel.setProperty("/SelectedModuleMain", data.SelectedModuleMain);
			this._globalModel.setProperty("/SelectedSubModuleMain", data.SelectedSubModuleMain);
			//this.getOwnerComponent().getModel("filterM").setData(ovar[selKey]);
			//this.createToken();
		},
		onSaveVariant: function (oEvent) {
			var thiz = this;
			var itemName = oEvent.getSource().data("itemName");
			var key = oEvent.getParameters().key;
			var bDefault = oEvent.getParameters().def;
			var varName = this.getVariantName(oEvent.getSource(), key);
			//var data = this.getOwnerComponent().getModel("filterM").getData();
			var data = {
				SelectedModuleMain: this._globalModel.getProperty("/SelectedModuleMain"),
				SelectedSubModuleMain: this._globalModel.getProperty("/SelectedSubModuleMain")
			};
			this.setFilterVariant(itemName, key, varName, data, bDefault, function (oCC) { // create item
				thiz.oCC1 = oCC;
			});
		},
		onManageVM: function (oEvent) {
			var oCC = this.oCC1;
			var itemName = oEvent.getSource().data("itemName");
			this.setManageVM(oEvent, oCC, itemName);
		},

		//******************************************end of variant *************************************

 

Secondly, users want to save data which they entered in the screen.For example, I entered some values in the page and saved this data with new name by pressing OK.

The important thing in here is that I updated the json data with new values entered by user before saving.

 

And, when you press manage button on popup after pressing Variant control, all layout is displayed and when you select a layout, ‘onSelectVariant‘ function is run and read data that had been saved before. Finally data is set for related controls in page.

 

 

Conclusion

In this article, I have tried to explain how to save data and how to read by using variant management control.  I think this code is useful for saving data and reading later. I mean, in this code part you can save and read data with format you wanted just only changing JSON data sections. Last thing, it is up to you how you will use data, and where you will put them.

Finally, you can adapt your screens using ‘save’, ‘delete’, ‘save as default’ functions as shown above code part.

 

 

 

References

https://sapui5.hana.ondemand.com/#/api/sap.ui.comp.variants.VariantManagement

https://blogs.sap.com/2018/08/23/fiori-variant-management-set-a-variant-as-default-to-all-users/

 

Süleyman Doğu

Assigned tags

      1 Comment
      You must be Logged on to comment or reply to a post.
      Author's profile photo Diego Güizzo
      Diego Güizzo
      Hi,
      Issue
      https://stackoverflow.com/questions/59749902/sapui5-variant-key-on-save-strange-behaviour
      On the onSaveAsVariant function add code to modify the id since it places an invalid one onSaveAsVariant
      enter code here
          var cantidadArray = oEvent.getSource().getVariantItems().length;
              if (cantidadArray > 0) {
                  var ddd = oEvent.getSource().getVariantItems()[0].getId().length;
                  var cadenaid = oEvent.getSource().getVariantItems()[0].getId().substring(0, ddd - 1);
                  var numeroanterior = oEvent.getSource().getVariantItems()[cantidadArray - 2].getId().substring(70, 71);
                  var snun = Number.parseInt(numeroanterior) + 1;
                  oEvent.getSource().getVariantItems()[cantidadArray - 1].sId = cadenaid + snun;
              }
      
      and then when saving the refresh is performed
          this.oContainer.save().done(function() {
                  this.onGetPersonalizer();
              }.bind(this));
      
      onGetPersonalizer: function() {
      
              var msg = 'Variante Guardada con exito';
              MessageToast.show(msg);
      
              var oComponent = sap.ui.core.Component.getOwnerComponentFor(this.getView());
              this.oPersonalizationService = sap.ushell.Container.getService("Personalization");
              var oPersId = {
                  container: "TablePersonalisation", //any
                  item: "DemoTableUI" //any- I have used the table name 
              };
              // define scope 
              var oScope = {
                  keyCategory: this.oPersonalizationService.constants.keyCategory.FIXED_KEY,
                  writeFrequency: this.oPersonalizationService.constants.writeFrequency.LOW,
                  clientStorageAllowed: true
              };
              // Get a Personalizer
              var oPersonalizer = this.oPersonalizationService.getPersonalizer(oPersId, oScope, oComponent);
              this.oPersonalizationService.getContainer("TablePersonalisation", oScope, oComponent)
                  .fail(function() {})
                  .done(function(oContainer) {
                      this.oContainer = oContainer;
                      this.oVariantSetAdapter = new sap.ushell.services.Personalization.VariantSetAdapter(this.oContainer);
                      // get variant set which is stored in backend
                      this.oVariantSet = this.oVariantSetAdapter.getVariantSet("DemoTableUISet");
                      if (!this.oVariantSet) { //if not in backend, then create one
                          this.oVariantSet = this.oVariantSetAdapter.addVariantSet("DemoTableUISet");
                      }
                      // array to store the existing variants
                      var Variants = [];
                      // now get the existing variants from the backend to show as list
                      for (var key in this.oVariantSet.getVariantNamesAndKeys()) {
                          if (this.oVariantSet.getVariantNamesAndKeys().hasOwnProperty(key)) {
                              var oVariantItemObject = {};
                              oVariantItemObject.VariantKey = this.oVariantSet.getVariantNamesAndKeys()[key];
                              oVariantItemObject.VariantName = key;
                              Variants.push(oVariantItemObject);
                          }
                      }
                      // create JSON model and attach to the variant management UI control
      
                      this.oVariantModel = new sap.ui.model.json.JSONModel();
      
                      this.oVariantModel.oData.variante = Variants;
                      this.getView().byId("idvariantManagement").setModel(this.oVariantModel, "variantes");
      
                      this.getView().byId("idvariantManagement").currentVariantSetModified(true);
      
                  }.bind(this));
              debugger;
              this.oTablepersoService.refresh();
          },
      

      that’s how it works for “Save As”, what doesn’t work is saving, since it has the same behavior that Br Nilesh Puranik comments

      I had the exact same problem recently but for the “Save” button. I have the same problem, did you find any solution?

      Thanks

      Diego Güizzo