How to mention action in httpProxy url when using extJS with Grails - grails

I am trying to integratae my Grails application with extJS.
Below is the code in my edit.gsp file.
<%# page import="tune.Music"%>
<script type="text/javascript">
var ds = new Ext.data.Store({
autoLoad: true,
proxy: new Ext.data.HttpProxy({
url: 'http://localhost:8080/tune/music/listData'}),
reader: new Ext.data.JsonReader({
results: 'total',
root:'items',
id:'id'
},
[
{name: 'playerId'},
{name: 'playerPrice'}
]
)
});
var cm = new Ext.grid.ColumnModel([
{header: "Player Id", width: 70, sortable:true, dataIndex: 'playerId'},
{header: "Player Price", width: 90, dataIndex: 'playerPrice'}
]);
//cm.defaultSortable = true;
// create the grid
var grid = new Ext.grid.GridPanel({
ds: ds,
cm: cm,
renderTo:'grid-example',
width:1300,
height:300
});
</script>
</head>
<body>
<div class="body">
<!--<g:javascript library="examples"/>-->
<!-- EXAMPLES -->
<h1>Ext Grid</h1>
<div id="grid-example"></div>
</div>
</body>
My controller action:
def list={
}
def listData = { def session = sessionFactory.getCurrentSession()
def result = session.createSQLQuery("select player_id from w.music where player_id=('530AS')").list();
def tuneInstanceList = new ArrayList()
result.each
{ def tune = new Tune()
tune.playerId = it
tune.playerPrice = "100"
tuneInstanceList.add(tune) }
def listResult = [total: tunInstanceList.size(), items: tunInstanceList]
render listResult as JSON;
}
The above code works for me.
However, This works in my development environment.
If I run this in another env it doesnt work because of the url that I have hardcoded here viz url: 'http://localhost:8080/tune/music/listData'.
One of the options is to use gsparse. However, i would like to mention a relative urlPath here if thats possible.
What do I replace my urlPath with so that the right action is called even in other environments.
Thanks!

replaced the HttpProxy url as
url: '/tune/music/listData' and it worked.
Thanks!

Related

.NET Kendo Scheduler: dynamically change datasource resources

Now i'm using a datasource like this: (with the parameters to filter hard coded)
$(function () {
$("#scheduler").kendoScheduler({
date: new Date(Date.now()),
startTime: new Date(2013, 5, 13, 9, 0, 0, 0),
height: 800,
timezone: "Etc/UTC",
group: {
resources: ["Rooms"]
},
resources: [
{
name:"Rooms",
title: "Room",
field: "RoomID",
dataSource: {
transport:
{
read: { url: "#Html.Raw(Url.Action("Filter_Rooms", "Room", new{
pPar1= true,
pPar2 = false,
pPar3 = true,
}))", dataType: "json" }
}
}
}
As you can see these paramaters are still hard coded and I want to change them whenever the user wants using checkboxes:
<div class="checkbox">
<label>
<input id="chkPar1" type="checkbox"> Parameter 1
</label>
</div>
<div class="checkbox">
<label>
<input id="chkPar2" type="checkbox"> Parameter 2
</label>
</div>
Filter
I thought while using javascript to check if button is clicked and then store checkbox paramaters in global variables and use these in the transport read of the scheduler but it seems you can't use document.getelementbyId here.
Here they suggested Kendo UI Dynamically Change Datasource String (XML) but that doesn't seem to work for me neither..
var dynamicUrl = "Html.Raw(Url.Action('Filter_Rooms', 'Room', new{pFilter = true, pCapacity = 25,pBeamer = true,pTelevision = false}))', dataType: 'json'"
var scheduler = $("#scheduler").data("kendoScheduler");
scheduler.dataSource.transport.options.read.url = dynamicUrl;
So How can I dynamically change these paramaters or update the entire transport read url?
Regards
Try this:
var pFilter = (document.getElementById("someID").value);
var pCapacity = document.getElementById("someID").value;
var pBeamer = document.getElementById("someID").value;
var pTelevision = document.getElementById("someID").value;
var dynamicUrl = "Html.Raw(Url.Action('Filter_Rooms', 'Room', new{pFilter = " + pFilter + ", pCapacity = " + pCapacity + ",pBeamer = " + pBeamer + ",pTelevision = " + pTelevision + "}))', dataType: 'json'"
There could be some type of string format that you could use like in C# but I'm not sure. Hope this works!
Not sure if it's exactly what you're after, but a good frame of reference might be this example project. It very simply shows how to load new content when you change the view. You may be able to adapt it.

Problems with loading events from rails generated JSON to FullCalendar by Angularjs

I'm new to AngularJS, and I've been trying this for a while but really cant solve my problem.
When I was using ui-calendar for Angular, it has the
"TypeError: undefined is not a function"
problem, and the calendar wont even show up.
I solved it by wrapping the scope.calendar to $(scope.calendar) in the calendar.js.
I saw other saying its because the dependency, but when the page is running I can find the js sources in the page like the following:
<script src="/assets/angular.min.js?body=1"></script>
<script src="/assets/fullcalendar.js?body=1"></script>
<script src="/assets/calendar.js?body=1"></script>
<script src="/assets/angular-resource.min.js?body=1"></script>
So is this a problem of dependency or?
The second problem I have is loading events from rails-generated json into my calendar.
$scope.events are events I wrote in javescript, $scope.eventjson are events from json, and only the $scope.events are loading into the calendar
I have this code in my rails controller:
respond_to do |format|
format.json { render :json => {:title=> "event", :start => "2014-04-08 10:00:00" }.to_json }
end
And this is my Angular Controller:
controller('myCtrl', ['$log', '$scope','$q', '$resource', '$http'].concat(function($log, $scope, $q, $resource, $http){
var date, d, m, y, Event;
date = new Date();
d = date.getDate();
m = date.getMonth();
y = date.getFullYear();
Event = $resource("/calendar.json");
$scope.eventjson = Event.get();
$scope.eventjson.$promise.then(function(result){
$scope.eventjson = result;
});
$scope.events = [
{
title: 'All Day Event',
start: "2014-4-10 10:00:00",
allDay: false
}, {
title: 'All Day Event',
start: "2014-4-11 10:00:00",
allDay: false
}
];
$scope.uiConfig = {
calendar: {
height: 350,
editable: true,
header: {
left: 'month basicWeek basicDay agendaWeek agendaDay',
center: 'title',
right: 'today prev,next'
},
defaultView: 'agendaWeek',
dayClick: $scope.dayClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
eventClick: $scope.eventClick,
viewRender: $scope.renderView
}
};
$scope.eventSources = [$scope.events] //this one works
//$scope.eventSources = [$scope.events, $scope.eventjson] //got Error: $interpolate:interr
//$scope.eventSources = [$scope.eventjson] //this one shows nothing
}));
And my view:
<div ui-calendar="uiConfig.calendar" ng-model="eventSources">
I personally think its related with angular's promise, but I think that shouldn't be because there is $scope.watch in the calendar.js which means it should be watching $scope.eventSources changes. But when using break points I can see $scope.eventsources are not loading value for $scope.eventSources = [$scope.eventjson].
I've been working on this for two days, really appreciate if someone can give some help.

kendo ui grid not showing data

I am trying to get this basic kendo ui with expandable rows working:
<div id="grid"></div>
<script type="text/javascript">
$(function () {
$("#grid").kendoGrid({
columns: [
{
field: "ProductId",
title: "ProductId"
}
],
dataSource: {
type: "json",
transport: {
read: '#Url.Action("GetData1", "MockForms")'
}
},
height: 450,
sortable: true,
pageable: true,
detailTemplate: "<h2 style='background-color: yellow;'>Expanded!</h2>",
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
}
});
});
</script>
The json is generated like this:
public ActionResult GetData1([DataSourceRequest] DataSourceRequest request)
{
var list = new List<Product>
{
new Product {ProductId = 1, ProductType = "SomeType 1", Name = "Name 1", Created = DateTime.UtcNow},
new Product {ProductId = 1, ProductType = "SomeType 2", Name = "Name 2", Created = DateTime.UtcNow},
new Product {ProductId = 1, ProductType = "SomeType 3", Name = "Name 3", Created = DateTime.UtcNow}
};
return Json(list.AsQueryable().ToDataSourceResult(request));
}
and seems to be send OK (according to firebug). However, nothing is bound (there are no javascript errors). Any ideas?
PS:
OnaBai's 2nd comment helped me to get this to work. I changed:
return Json(list.AsQueryable().ToDataSourceResult(request));
=>
return Json(list);
which produces this JSON:
[{"ProductId":1,"ProductType":"SomeType 1","Name":"Name 1","Created":"\/Date(1371022051570)\/"},{"ProductId":1,"ProductType":"SomeType 2","Name":"Name 2","Created":"\/Date(1371022051570)\/"},{"ProductId":1,"ProductType":"SomeType 3","Name":"Name 3","Created":"\/Date(1371022051570)\/"}]
Still I would like to use:
return Json(list.AsQueryable().ToDataSourceResult(request));
as this will eventually make paging and sorting easier. It currently produces:
{"Data":[{"ProductId":1,"ProductType":"SomeType 1","Name":"Name 1","Created":"\/Date(1371022186643)\/"},{"ProductId":1,"ProductType":"SomeType 2","Name":"Name 2","Created":"\/Date(1371022186648)\/"},{"ProductId":1,"ProductType":"SomeType 3","Name":"Name 3","Created":"\/Date(1371022186648)\/"}],"Total":3,"AggregateResults":null,"Errors":null}
I tried to use:
field: "Data.ProductId",
instead of:
field: "ProductId",
in the JavaScript code with no avail.
If you want to use ToDataSourceResult you should use the ASP.NET MVC wrappers. More info is available in the documentation: http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding

Backbone.js - How to save model by form and post to server

I'm n00b in BackboneJS/RequireJS and I'm developing an web app that use a RESTful API.
So I've a model like this:
models/pet.js
define([
'backbone'
], function(Backbone){
var PetModel = Backbone.Model.extend({
urlRoot: 'http://localhost:3000/pet',
idAttribute: '_id',
defaults: {
petId: "",
type: "",
name: "",
picture: "",
description: "",
breed: "",
size: "",
sex: "",
age: "",
adopted: false,
}
});
return PetModel;
});
a collection: collections/pets.js
define([
'backbone',
'models/pet'
], function(Backbone, PetModel){
var PetsCollection = Backbone.Collection.extend({
url: 'http://localhost:3000/pets',
model: PetModel,
});
return PetsCollection;
});
And a view that renders a form to add new models (Maybe it's possible another way more elegant)
views/petAddNew.js
define([
'jquery',
'backbone',
'models/pet',
'collections/pets',
'text!templates/pet/addNew.html'
], function($, Backbone, PetModel, PetsCollection, petAddNewTemplate){
var PetAddNewView = Backbone.View.extend({
el: $('#formAdd'),
template: _.template(petAddNewTemplate),
events: {
'click #add' : 'submitAdd',
},
initialize: function() {
this.model = new PetModel();
this.collection = new PetsCollection();
_.bindAll(this, 'submitAdd');
},
render: function() {
var view = this;
view.$el.html( view.template );
return view;
},
submitAdd: function(e) {
//Save Animal model to server data
e.preventDefault();
var pet_data = JSON.stringify( this.getFormData( this.$el.find('form') ) );
this.model.save(pet_data);
this.collection.add(this.model);
return false
},
//Auxiliar function
getFormData: function(form) {
var unindexed_array = form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
},
});
return PetAddNewView;
});
So when I submit the form I don't post any data to server. I don't know how to fix it.
Any ideas? Thanks in advance!
You need set the attributes first and then save.
//Auxiliar function
getFormData: function(form) {
var self = this;
var unindexed_array = form.serializeArray();
$.map(unindexed_array, function(n, i){
self.model.set({
n['name']: n['value']
});
});
}
Now this.model.save() works (saving on the server side).
You can see it work in a fiddle.
Model.save expect an object/hash of new values, just like Model.set. Here you're passing a string as the attributes arguments.

Reading parameters enterd on the screen

I have a page that accepts parameters from the user. I read this parameter in my action using params.playerId. and then do the computations with it.
I have changed my UI now and am using extJS for display purposes.
Therefore I have an edit and an editData action.
editData action has the code to run the sql and execute the appropriate js file and displays edit.jsp. However, in the editData action, when I use params.playerId, I get a null value.
What can be a work round for this scenario?
My code before integrating with extJS: list action is called and list.gsp is displayed with data.
def list = {
def session = sessionFactory.getCurrentSession()
def result = session.createSQLQuery("select player_id from w.music where player_id=(params.playerId)").list();
def tuneInstanceList = new ArrayList()
def tune = new Tune()
result.each
{
tune.playerId = it
tune.playerPrice = "100" tuneInstanceList.add(tune)
}
[recoveryInstanceList: recoveryInstanceList]
}
Now, when I ntegrate with extJS, I get the value of params.playerId as null. Code is below.
list.gsp:
<%# page import="tune.Music"%>
<script type="text/javascript">
var ds = new Ext.data.Store({
autoLoad: true,
proxy: new Ext.data.HttpProxy({
url: 'http://localhost:8080/tune/music/listData'}),
reader: new Ext.data.JsonReader({
results: 'total',
root:'items',
id:'id'
},
[
{name: 'playerId'},
{name: 'playerPrice'}
]
)
});
var cm = new Ext.grid.ColumnModel([
{header: "Player Id", width: 70, sortable:true, dataIndex: 'playerId'},
{header: "Player Price", width: 90, dataIndex: 'playerPrice'}
]);
//cm.defaultSortable = true;
// create the grid
var grid = new Ext.grid.GridPanel({
ds: ds,
cm: cm,
renderTo:'grid-example',
width:1300,
height:300
});
</script>
<div class="body">
<!--<g:javascript library="examples"/>-->
<!-- EXAMPLES -->
<h1>Ext Grid</h1>
<div id="grid-example"></div>
</div>
My controller action:
def list={ }
def listData = {
def session = sessionFactory.getCurrentSession()
def result = session.createSQLQuery("select player_id from w.music where player_id= (params.playerId)").list();
def tuneInstanceList = new ArrayList()
result.each {
def tune = new Tune()
tune.playerId = it tune.playerPrice = "100"
tuneInstanceList.add(tune)
}
def listResult = [total: tunInstanceList.size(), items: tunInstanceList]
render listResult as JSON;
}
How can I retrieve the parameters that have been entered by the user??
Thanks!
Worked around this issue by reading the parameters in list() action and saving it in a session.
Then used this session data in the listData() action to do the computations.
Not sure if this is the best approach. This is just a workaround.

Resources