2

I want to pass values from a view to controller on button press.In view am passing productJson which is an object.But i am unable to retrieve that value in controller.Please help.

View js:

 new sap.m.Button({
         text: "Add to Cart",
         press:[oController.addtoCartBtnPress,oController,productJson],
        })

Controller js:

 addtoCartBtnPress:function(e,oView,productJson)
      {
      }

Result:

oView and productJson values are returned as undefined.

1 Answer 1

9

The data should be first value in the press array. Per the sdk docs for sap.m.Button:

press : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]

The listener function should then have 2 arguments: 1-the event; and 2- the data.

onPressFn: function(evt, data) { ... }

To get the view, just use:

var view = this.getView();
  • "this" will be equal to whatever you pass as the third value in the press array, and should usually be the controller in order to match the behaviour of xml/html views.

And an alternative to passing the data in the press call would be to use the view-model binding, especially if you are already using that model binding elsewhere in the view. But it depends how many products you have and other factors so I won't assume it will be ideal for your case.

//in the view
var productModel = new sap.ui.model.json.JSONModel(productJson);
view.setModel(productModel, "product");

//in the controller:
var data = view.getModel("product").getData();
2
  • Thanks.I figured out this and it worked.Thanks anyway.Now I want pass values between two controllers.How to do that?
    – Papu
    Jan 3, 2014 at 10:40
  • 2
    1. Get controller reference with sap.ui.getCore().byId("idOfDesiredView").getController(); precondition: you have to give your JS/HTML/XMLView a unique id when creating. 2. Attach the desired data to the navigation between the controllers. 3. Store controller references globally
    – cschuff
    Jan 24, 2014 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.