aurelia bridge kendo grid refresh - kendo-grid

I'm trying to use Aurelia KendoUi Bridge in my application.
In my code I have a service which returns a new KendoDataSource :
export class KendoDataSource {
ToKendoDataSource(data: any, recordCount: number, pageSize: number, currentPage: number): any {
return {
transport: {
read: (p) => {
p.success({ data: data, recordCount: recordCount });
}
},
pageSize: pageSize,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
schema: {
data: (result) => {
console.log('Transforming data to kendo datasource.');
return result.data;
},
total: (result) => {
return result.recordCount;
}
}
};
}
}
And this is my viewModel:
#inject(HttpService, KendoDataSource, EventAggregator)
export class GroupList {
grid: any;
gridVM: any;
datasource: any;
pageable: any;
subscriber: any;
paginationDetailsRequest: PaginationDetailsRequest;
test: string;
constructor(private httpService: HttpService, private kendoDataSource: KendoDataSource, private eventAggregator: EventAggregator) {
this.httpService = httpService;
this.kendoDataSource = kendoDataSource;
this.eventAggregator = eventAggregator;
this.paginationDetailsRequest = new PaginationDetailsRequest(4, 1);
this.GetGroups(this.paginationDetailsRequest);
this.datasource = {
transport: {
read: {
url: 'PersonGroup/GetGroups',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json'
},
parameterMap: function (data, type) {
if (type == "read") {
let paginationDetails = new PaginationDetailsRequest(data.pageSize, data.page);
if(data.sort && data.sort.length > 0){
paginationDetails.orderBy = data.sort[0].field;
paginationDetails.OrderDesc = (data.sort[0].dir == 'desc');
}
console.log(this.datasource);
return JSON.stringify(paginationDetails);
}
}
},
schema: {
data: "data.currentPageData",
total: "data.totalCount"
},
pageSize: 2,
serverPaging: true,
serverFiltering: true,
serverSorting: true
};
};
attached() {
this.subscriber = this.eventAggregator.subscribe('Search', response => {
this.search(response);
});
}
activate() {
this.pageable = {
refresh: true,
pageSizes: true,
buttonCount: 10
};
}
GetGroups(paginationDetails: PaginationDetailsRequest): void {
this.httpService.post('PersonGroup/GetGroups', paginationDetails)
.then(response => response.json())
.then(groups => {
console.log(groups);
if (groups.succeeded) {
this.datasource = this.kendoDataSource.ToKendoDataSource(groups.data.currentPageData, groups.totalCount, groups.pageSize, groups.currentPage);
this.grid.setDataSource(this.datasource); // initialize the grid
}
else {
//TODO: Show error messages on screen
console.log(groups.errors);
}
})
.catch(error => {
//TODO: Show error message on screen.
console.log(error);
});
}
search(searchDetails: Filter) {
console.log(searchDetails);
this.paginationDetailsRequest.filters.push(searchDetails);
console.log(this.paginationDetailsRequest);
this.GetGroups(this.paginationDetailsRequest);
}
detached() {
this.subscriber.dispose();
}
}
I understand that kendo does not have two-way data binding, But I'm trying to find a way to refresh the grid when I filter the data and the data source has changed.
Thanks.

I had this problem and found the solution by creating a new dataSource and assigning it to setDataSource, as follows... Note, getClients() is a search activated by a button click.
Here is the grid:
<ak-grid k-data-source.bind="datasource"
k-pageable.bind="{ input: true, numeric: false}"
k-filterable.bind="true"
k-sortable.bind="true"
k-scrollable.bind="true"
k-widget.bind="clientgrid"
k-selectable.bind="true">
<ak-col k-title="First Name" k-field="firstName" k-width="120px"></ak-col>
<ak-col k-title="Last Name" k-field="lastName" k-width="120px"></ak-col>
<ak-col k-title="Email Address" k-field="primaryEmail" k-width="230px"></ak-col>
</ak-grid>
And here is the code that updates the dataSource
public getClients()
{
console.log("ClientService.getClients");
this.clientService.getClients()
.then(result =>
{
this.clientList = result;
// the new datasource in the next line is displayed
// after the call to setDataSource(ds) below.
let ds: kendo.data.DataSource = new kendo.data.DataSource({
data: this.clientList,
schema: {
model: {
id: "id",
fields: {
firstName: { type: 'string' },
id: { type: 'number' },
lastName: { type: 'string' },
primaryEmail: { type: 'string' }
}
}
},
pageSize: 10
});
this.clientgrid.setDataSource(ds);
this.clientgrid.refresh();
})
.catch(err => console.log("Error returned from getClients " + err));
}

You don't really need to create a brand new datasource. To refresh the grid after changing the underlying data you can just replace the data element in the dataSource like so:
this.clientgrid.dataSource.data(this.datasource.data);

Related

KendoGrid: can't disable autosync + all other lines are disabled after "destroy"

I tried so solve this for a while now, but cannot find the solution.
I cannot disable autosync for some reason. Everytime I click on "destroy" for a single row, transport.submit is triggered (and would send data to the server). I actually only want to trigger submit once, when I click the "save" button.
Is this expected behaviour? Should I handle the server communications externaly and only save locally in transport.submit? Or am I doing something wrong?
Once I remove one item using the "destroy" button, all other items are disabled until I press the "cancel" button.
How can I avoid this?
Here is my Code:
$(document).ready(function () {
var myData = getDataSource();
var dataGrid = $("#divOverview").kendoGrid({
dataSource: myData,
sortable: true,
filterable: true,
pageable: true,
toolbar: ["save", "cancel"],
columns: [
// Dataworld
{ field: "Dataworld", width: "180px" },
// Servername
{ field: "Servername"},
// IPAddress
{ field: "IPAddress"},
// Commands
{ command: ["destroy"], title: " ", width: "250px" }
],
editable: {
mode: "inline",
confirmation: false
}
});
});
function getDataSource(){
var datasource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax({
url: "../AccountSyncConfig/GetAccountSyncConfig.erb",
dataType: "json",
data: {mandatorID: mandatorID},
success: function(result) {
options.success(result);
},
error: function(result) {
options.error(result);
}
});
},
submit: function(e) {
var data = e.data;
console.log(data);
},
parameterMap: function(data, type) {
if (type == "read") {
return { mandatorID: mandatorID};
} else if (type == "submit") {
//console.log( {models: JSON.stringify(data.models)} );
return {
data: kendo.stringify({
mandatorID: mandatorID,
models: data.models
})
};
} else {
return "";
}
}
},
schema: {
model: {
id: "EntryID",
fields: {
Dataworld: {
type: "string",
validation: {
required: true
}
},
Servername: {
type: "string",
validation: {
required: true
}
},
IPAddress: {
type: "string",
validation: {
required: true,
IPAddressvalidation: function (input) {
if (input.val() != "") {
input.attr("data-IPAddressvalidation-msg", "Ungültige IP-Adresse");
return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(input.val());
}
return true;
}
}
}
},
}
},
autoSync: false,
batch: true,
pageSize: 10
});
return datasource;
}

Unable to populate json to FormArray. TypeError: data.map is not a function

I am receiving this json format from api and need to populate it into FormArray. But am getting TypeError: data.map is not a function. Below is the code snippet.
{
"data": [
{
"id": "ASR4324368",
"name": "TTTTT",
"amount": 100
},
{
"id": "GTH435435435",
"name": "AAAAA",
"amount": 500
}
]
}
getProductJson() {
this.httpClient.request('GET', 'getProductJSON', { withCredentials: true })
.subscribe(
(data: any[]) => {
this.productForm = this.fb.group({
product: this.fb.array(
data.map(datum => this.generateDatumFormGroup(datum))
)
});
},
error => {
console.log(error);
}
);
}
private generateDatumFormGroup(datum) {
return this.fb.group({
id: this.fb.control({ value: datum.id, disabled: false }),
productName: this.fb.control({ value: datum.name, disabled: false }),
productAmt: this.fb.control({ value: datum.amount, disabled: false }),
});
}
are you sure you get data? to check use pipe(tap)
this.httpClient.request('GET', 'getProductJSON', { withCredentials: true })
.pipe(tap(res=>{console.log(res)})) //<--add this line
.subscribe(....rest-of your code...)
NOTE: I feel strange your request (but really I don't know if is ok) I ususally use some like
this.httpClient.get('http://myapi/api/controller/action', { withCredentials: true })
Modified to the below and was working.
getProductJson() {
this.httpClient.request('GET', 'getProductJSON', { withCredentials: true })
.subscribe(
(data: any[]) => {
this.raw = data;
this.productObj = this.raw.data;
this.productForm = this.fb.group({
product: this.fb.array(
this.productObj.map(datum => this.generateDatumFormGroup(datum))
)
});
},
error => {
console.log(error);
}
);
}

Custom type in GraphQL mutation

I am using GraphQL js.I want to implement One-to-many association in it.I have two types user and Office.One user has many offices.
userType:
var graphql = require('graphql');
const userType = new graphql.GraphQLObjectType({
name: 'user',
fields :()=>{
var officeType=require('./officeSchema');
return {
_id: {
type: graphql.GraphQLID
},
name: {
type: graphql.GraphQLString
},
age: {
type: graphql.GraphQLString
},
office:{
type:officeType
}
};
}
});
module.exports=userType;
officeSchema:
const officeType = new graphql.GraphQLObjectType({
name: 'office',
fields:()=> {
var userType = require('./userSchema');
return {
_id: {
type: graphql.GraphQLID
},
room: {
type: graphql.GraphQLString
},
location: {
type: graphql.GraphQLString
},
users: {
type: new graphql.GraphQLList(userType),
resolve: (obj,{_id}) => {
fetch('http://0.0.0.0:8082/office/user/'+obj._id, {
method: "GET",
headers: {
'Content-Type': 'application/json'
}
})
.then(function(res) {return res});
}
}
};
}
});
Now the mutation code is as follows:
const Adduser = {
type: userType,
args: {
name: {
type: graphql.GraphQLString
},
age: {
type: graphql.GraphQLString
}
},
resolve: (obj, {
input
}) => {
}
};
const Addoffice = {
type: OfficeType,
args: {
room: {
type: graphql.GraphQLString
},
location: {
type: graphql.GraphQLString
},
users: {
type: new graphql.GraphQLList(userInputType)
}
},
resolve: (obj, {
input
}) => {
}
};
const Rootmutation = new graphql.GraphQLObjectType({
name: 'Rootmutation',
fields: {
Adduser: Adduser,
Addoffice: Addoffice
}
});
This code is throwing error as
Rootmutation.Addoffice(users:) argument type must be Input Type but got: [user].
I want to add the actual fields in database as well as associated tables' fields but couldn't figure out the problem.
Updated:
1-Added GraphQLInputObjectType:
const officeInputType = new graphql.GraphQLInputObjectType({
name: 'officeinput',
fields: () => {
return {
room: {
type: graphql.GraphQLString
},
location: {
type: graphql.GraphQLString
}
}
}
});
const userInputType = new graphql.GraphQLInputObjectType({
name: 'userinput',
fields: () => {
return {
name: {
type: graphql.GraphQLString
},
age: {
type: graphql.GraphQLString
}
}
}
});
2-Added userinputtype instead of usertype in AddOffice.
Now the error is
Rootmutation.Addoffice(user:) argument type must be Input Type but got: userinput.
The problem is that you provided userType as one of the argument types for the Addoffice mutation. userType cannot be an argument type. Instead, you must use an input type.
There are two object types: output and input types. Your userType and officeType are output types. You need to create an input type using GraphQLInputObjectType [docs]. It will likely have very similar fields. You can use that as a type on your argument field.
const userInputType = new graphql.GraphQLInputObjectType({
name: 'UserInput',
fields () => {
return {
_id: {
type: graphql.GraphQLID
},
// ...
};
}
});

Load form data via REST into vue-form-generator

I am building a form, that needs to get data dynamically via a JSON request that needs to be made while loading the form. I don't see a way to load this data. Anybody out here who can help?
JSON calls are being done via vue-resource, and the forms are being generated via vue-form-generator.
export default Vue.extend({
template,
data() {
return {
model: {
id: 1,
password: 'J0hnD03!x4',
skills: ['Javascript', 'VueJS'],
email: 'john.doe#gmail.com',
status: true
},
schema: {
fields: [
{
type: 'input',
inputType: 'text',
label: 'Website',
model: 'name',
maxlength: 50,
required: true,
placeholder: companyList
},
]
},
formOptions: {
validateAfterLoad: true,
validateAfterChanged: true
},
companies: []
};
},
created(){
this.fetchCompanyData();
},
methods: {
fetchCompanyData(){
this.$http.get('http://echo.jsontest.com/key/value/load/dynamicly').then((response) => {
console.log(response.data.company);
let companyList = response.data.company; // Use this var above
}, (response) => {
console.log(response);
});
}
}
});
You can just assign this.schema.fields.placeholder to the value returned by the API like following:
methods: {
fetchCompanyData(){
this.$http.get('http://echo.jsontest.com/key/value/load/dynamicly').then((response) => {
console.log(response.data.company);
this.schema.fields.placeholder = response.data.company
}, (response) => {
console.log(response);
});
}
}

No HTTP resource was found that matches the request URI 'http://localhost:xxx:

I am working on .net web api.....
Web Api Config :
public static void Register(HttpConfiguration config)
{
// Verb Routing
RouteTable.Routes.MapHttpRoute(
name: "SmallBizApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new
{
id = RouteParameter.Optional,
action = RouteParameter.Optional
}
);
config.Formatters.Clear();
config.Formatters.Insert(0, new SmallBiz.WebAPI.Common.JsonpFormatter());
}
I am using jsonp format to load data in kendo-ui Gantt chart as can be seen...
<div id="grid"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function () {
var projectdata = "http://localhost:1799/api",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: projectdata + "/project",
dataType: "jsonp"
},
update: {
url: projectdata + "/project/put",
dataType: "jsonp"
},
destroy: {
url: projectdata + "/project/delete",
dataType: "jsonp"
},
create: {
url: projectdata + "/project/post",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProjectId",
fields: {
ProjectId: { editable: false, nullable: false },
Name: { validation: { required: true } },
Status: { validation: { required: true } },
IsActive: { type: "boolean" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
toolbar: ["create"],
scrollable: false,
sortable: true,
groupable: true,
columns: [
{ field: "Name", title: "Project Name", width: "170px" },
{ field: "Status", title: "Status", width: "110px" },
{ field: "IsActive", title: "Active", width: "50px" },
{ command: ["edit", "delete", "Setting","Task"], title: " ", width: "150px" }
],
editable: "popup"
});
});
</script>
Controller code :
public IQueryable<ProjectsDM> GetProject()
{
return db.Project;
}
[HttpPut]
public IHttpActionResult PutProjectsDM(int id, ProjectsDM projectsdm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != projectsdm.ProjectId)
{
return BadRequest();
}
db.Entry(projectsdm).State = EntityState.Modified;
try
{
projectsdm.ModifiedBy = "adnan";
projectsdm.ModifiedDate = DateTime.Now;
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProjectsDMExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
Get method/action is working fine in kendo grid but i face problem
with put method/action(when we try to edit some record in grid)....
The errors in firebug .net tab
Response : "Message": "No HTTP resource was found that matches the
request URI 'http://localhost:1799/api/project
/put?callback=jQuery191012879030621062526_1433486934717&models=[{\"ProjectId\":2%2C\"ClientId\":1%2C
\"FirmId\":1%2C\"Status\":\"Started\"%2C\"Name\":\"Flexi77\"%2C\"IsActive\":true%2C\"CreatedDate\":\"2015-06-03T00
:00:00\"%2C\"ModifiedDate\":\"2015-06-03T00:00:00\"%2C\"CreatedBy\":\"adnan\"%2C\"ModifiedBy\":\"adnan
\"}]&_=1433486934719'.",
> "MessageDetail": "No action was found on the controller 'Project'
that matches the name 'put'."
json : "No action was found on the controller 'Project' that matches
the name 'put'."
Is there some route error or stupid mistake, please do help....
any kind of hint/help is much appreciated....
thanks for your time
The problem is that your Web API action expects two parameters:
int id, it's missing from the request URL
ProjectsDM projectsdm, can be retrieved from the payload (request body)
You need to use an URL that includes the missing id parameter. In the route template it's optional, but, if it's missing, as the action which requires it, the action cannot be chosen by the action selector.
So either add the id to the URL, or remove the id parameter from the action.