SAP UI5 - How to pass values for a controller? - parameter-passing

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.

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();

Related

calling a dojo JsonRest with parameters

When calling JsonRest using dojo, how can I pass parameters with it.
var rest = new JsonRest({
target: "/path/to/service"
});
JsonRest example:
require(["dojo/store/JsonRest"], function(JsonRest){
// create a store with target your service
var store = new JsonRest({
target: "/path/to/service"
});
// make a get request passing some options
store.query("foo=bar", {
start: 5,
count: 5,
sort: [
{ attribute: "color", descending: true }
]
}).then(function(results){
// result here
});
});
The function to use in your case is query with signature query(query, options)
When called, query will trigger a GET request to {target}?{query}, as described in dojo docs.
Please keep in mind that:
If query is an object, it will be serialized.
If query is a string, it is appended to the URL as-is.
If options includes a sort property, it will be serialized as a query parameter as well;
Your service/API should:
Return a array of objects in JSON format.
Return an empty array if no match is found.

How to get a list via POST in Restangular?

Consider a REST URL like /api/users/findByCriteria which receives POSTed JSON that contains details of the criteria, and outputs a list of Users.
How would one call this with Restangular so that its results are similar to Restangulars getList()?
Restangular.all('users').post("findByCriteria", crit)... might work, but I don't know how to have Restangular recognize that the result will be a list of Users
Restangular.all('users').getListFromPOST("findByCriteria", crit)... would be nice to be able to do, but it doesn't exist.
Doing a GET instead of a POST isn't an option, because the criteria is complex.
Well,
I experience same problem and I workaround it with plain function, which return a plain array of objects. but it will remove all Restangular helper functions. So, you cant use it.
Code snippet:
Restangular.one('client').post('list',JSON.stringify({
offset: offset,
length: length
})).then(
function(data) {
$scope.clients = data.plain();
},
function(data) {
//error handling
}
);
You can get a POST to return a properly restangularized collection by setting a custom handler for OnElemRestangularized in a config block. This handler is called after the object has been Restangularized. isCollection is passed in to show if the obect was treated as a collection or single element. In the code below, if the object is an array, but was not treated as collection, it is restangularized again, as a collection. This adds all the restangular handlers to each element in the array.
let onElemR = (changedElem, isCollection, route, Restangular: restangular.IService) => {
if (Array.isArray(changedElem) && !isCollection ) {
return Restangular.restangularizeCollection(null, changedElem, changedElem.route);
}
return changedElem;
};
RestangularProvider.setOnElemRestangularized(onElemR);

Zend Jquery Autocomplete populate from Database

Hi I am trying to implement a autocomplete field using Zend Jquery. I followed a tutorial to grab the data from an array and I have extended the code to access the data from my mysql table.
IndexController.php
$this->view->autocompleteElement = new ZendX_JQuery_Form_Element_AutoComplete('ac');
$this->view->autocompleteElement->setLabel('Autocomplete');
$this->view->autocompleteElement->setJQueryParam('source', '/index/city');
This calls the cityAction()
public function cityAction()
{
$results = Application_Model_City::search($this->_getParam('term'));
$this->_helper->json(array_values($results));
}
I then call the Model City
public static function search($term)
{
$region = new Application_Model_DbTable_Regions();
$results = $region->getRegion($term);
return $results;
}
And finally the Regions db model
public function getRegion($term)
{
$select = $this->select()->from($this,'City')
->where('City LIKE ? ',$term.'%');
return $this->fetchAll($select)->toArray();
}
Now when I go the autocomplete field it shows the results but as UNDEFINED , I think its something to do the way I am send the data back to the json helper.
I used firebug and I can see the data is been pulled in the following format.
[{"City":"London"},{"City":"Londonderry"},{"City":"Longfield"},{"City":"Longhope"},{"City":"Longniddry"}]
I think this format is incorrect, please any body dealt with this before?
Cheers
J
The ZendX_JQuery_Form_Element_AutoComplete element is a proxy to the AutoComplete View Helper, which is a proxy to the jQuery UI Autocomplete widget.
If you read the overview on the jQuery UI Autocomplete page, you will note:
The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.
When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.
So, the JSON you are returning to the autocomplete should be structured more like:
[{"label":"London","value":"London"},{"label":"Londonderry","value":"Londonderry"},{"label":"Longfield","value":"Longfield"}]
Good luck!
Fixed the problem afters hours of pain!
I modified the below code where it accesses the data
public function getRegion($term)
{
$select = $this->select()->from($this,'City')
->where('City LIKE ? ',$term.'%');
return $this->fetchAll($select)->toArray();
}
I added a line of SQL City AS Value
public function getRegion($term)
{
$select = $this->select()->from($this,'City AS value')
->where('City LIKE ? ',$term.'%');
return $this->fetchAll($select)->toArray();
}
This seems to have worked!
Cheers
J

asp.net mvc 3 ViewModel collection property to json not working

Good evening everyone. I am currently using MVC 3 and I have a viewmodel that contains a property that is a List. I am currently using json2's JSON.stringify method to pass my viewmodel to my action method. While debugging I am noticing that all the simple properties are coming thru but the collection property is empty even though I know for sure that there is at least one object in the collection. I wanted to know if there is anyone that is running into the same issue. Below is the code that I am using to post to the action method:
$.post("/ReservationWizard/AddVehicleToReservation/",
JSON.stringify('#ViewData["modelAsJSON"]'),
function (data) {
if (data != null) {
$("#vehicle-selection-container").html(data);
$(".reservation-wizard-step").fadeIn();
}
});
The object #ViewData["modelAsJSON"] contains the following json and is passed to my action method
{"NumberOfVehicles":1,"VehiclesToService":[{"VehicleMakeId":0,"VehicleModelId":0}]}
As you can see the property "VehiclesToService" has one object but when it gets to my action method it is not translated to the corresponding object in the collection, but rather the collection is empty.
If anyone has any insight into this issue it would be greatly appreciated.
Thanks in advance.
UPDATE
OK after making the recommended changes and making the call to new JavaScriptSerializer().Serialize(#Model) this is the string that ultimately gets sent to my action method through the post
'{"NumberOfVehicles":1,"VehiclesToService":[{"VehicleMakeId":0,"VehicleModelId":0}]}'
I can debug and see the object that gets sent to my action method, but again the collection property is empty and I know that for sure there is at least one object in the collection.
The AddVehicleToReservation action method is declared as follows:
public ActionResult AddVehicleToReservation(VehicleSelection selections)
{
...
return PartialView("viewName", model);
}
Here's the problem:
JSON.stringify('#ViewData["modelAsJSON"]')
JSON.stringify is a client side function and you are passing as argument a list that's stored in the ViewData so I suppose that it ends up calling the .ToString() and you have
JSON.stringify('System.Collections.Generic.List<Foo>')
in your final HTML which obviously doesn't make much sense. Also don't forget that in order to pass parameters to the server using the $.post function the second parameter needs to be a javascript object which is not what JSON.stringify does (it generates a string). So you need to end up with HTML like this:
$.post(
'ReservationWizard/AddVehicleToReservation',
[ { id: 1, title: 'title 1' }, { id: 2, title: 'title 2' } ],
function (data) {
if (data != null) {
$('#vehicle-selection-container').html(data);
$('.reservation-wizard-step').fadeIn();
}
}
);
So to make this work you will first need to serialize this ViewData into JSON. You could use the JavaScriptSerializer class for this:
#{
var myList = new JavaScriptSerializer().Serialize(ViewData["modelAsJSON"]);
}
$.post(
'#Url.Action("AddVehicleToReservation", "ReservationWizard")',
// Don't use JSON.stringify: that makes JSON request and without
// proper content type header your sever won't be able to bind it
#myList,
function (data) {
if (data != null) {
$('#vehicle-selection-container').html(data);
$('.reservation-wizard-step').fadeIn();
}
}
);
And please don't use this ViewData. Make your views strongly typed and use view models.

Reloading a json store with new parameters ExtJs Ext.data.JsonStore

I am currently having trouble of reloading a json store with new parameters. Here is my store:
newsletters = new Ext.data.JsonStore({
url: '/newsletters/',
root: 'results',
fields: [
'id',
'body'
'recipients'
],
baseParams: { command: 'json', to: dateTo, from: dateFrom },
autoLoad: true
});
dateTo and dateFrom are initally empty strings ( '' ) and checking in firebug /newsletters is called with the correct parameters.
Now none of the following techniquest work:
Changing the values of dateTo and dateFrom then calling newsletters.reload() still calls the page with the parameters to and from being empty strings.
Calling newsletters.reload( { to: 'test1', from: 'test2' } ); still sees the parameters as empty strings.
Finally as from the manual I have tried:
lastOptions = newsletters.lastOptions;
Ext.apply(lastOptions.params, {
to: 'test1',
from: 'test2'
});
newsletters.reload(lastOptions);
This again does not request /newsletters with the updated parameters.
Any advice appreciated!
You can actually pass params object to the load() method
newsletters.load({
params: {to: 'test1', from: 'test2'}
})
From the docs, you can probably do :
store.setBaseParam('to', dateTo);
Now, if I understand correctly, you want your baseParams to be changed whenever dateTo and dateFrom are changed.
You could try :
var dateTo = '', dateFrom = '';
store.on('beforeload', function(s) {
s.setBaseParam('to', dateTo);
s.setBaseParam('from', dateFrom);
});
// This should work :
dateTo = 1;
dateFrom = 2;
store.load();
My problem was: I have a store that shall request data over a proxy to back-end. This request shall hold a parameter named filter, which will just help back-end to decide which is the set of result the client is interested in. This parameter is loaded from a Combobox or some other component which the user can use to express which filter shall be used.
From my point of view the parameters shouldn't be set to the Store and neither using the load parameter. I will explain why:
Configuring parameters to the store would imply that every other component using the same store will have this parameters configured, meaning you can have concurrence problems.
And on the second case, it is not interesting to have it configurable over load method, because you don't wanna every single time explicit make use of the load method by your self, remember that there are already some components like paging and custom components that triggers this method.
What would be the right way from my point of view:
Every time that a load is triggered, we just attach the additional parameter in a non-intrusive way. Meaning that the trigger will not need to have any change (remember here trigger could be any component that executes store.load()) and the store shall be not aware about this new parameter.
You can see here clearly that this shall be an operation done before request data to proxy, and in my case I implemented as a listener for the beforeload event. When beforeload is executed, I just aggregate the new parameters to the operation parameter of the listener that according documentation is: beforeload( store, operation, eOpts ). The final implementation is something like:
store.on({
beforeload: function (store, operation, opts) {
Ext.apply(operation, {
params: {
filterName: Ext.getCmp('filterCombo').getValue()
}
});
}
});