Breeze issue with complexType change tracking - breeze

I use Angular and Breeze in my app and I use "hasChangesChanged" event for handling a state of entities stored in EntityManager. I have a problem when I have entity with property that is complexType and isScalar=false.
The problem occurs when I make request twice (without changing any entity) and get the same entity. On second request "hasChangesChanged" event is fired with hasChanges=true.
In moment when this event is fired my entity has state "Modified", but after data are loaded that state is changed to "Unchanged".
I've wrote a (Jasmine) unit test. In comments are information which assertion throws error.
var entity,
hasChanges = false,
listeners = {
onChange: function (event) {
console.log('change', event.hasChanges);
}
};
spyOn(listeners, 'onChange');
$httpBackend.expectGET('json/SampleEntity?').respond(200, [
{
id: 1,
name: 'some name',
data: {},
$type: 'SampleEntity',
elements: [
{
etype: 'el1'
}
]
}
]);
manager.hasChangesChanged.subscribe(function (event) {
hasChanges = event.hasChanges;
});
var query = new breeze.EntityQuery('SampleEntity');
manager.executeQuery(query).then(function (data) {
entity = data.results[0];
});
$httpBackend.flush();
expect(hasChanges).toBe(false); // OK
expect(entity.entityAspect.entityState.isUnchanged()).toBe(true); // OK
$httpBackend.expectGET('json/SampleEntity?').respond(200, [
{
id: 1,
name: 'some name',
data: {},
$type: 'SampleEntity',
elements: [
{
etype: 'el1'
}
]
}
]);
manager.executeQuery(query).then(function (data) {
entity = data.results[0];
});
$httpBackend.flush();
expect(hasChanges).toBe(false); // ERROR
expect(entity.entityAspect.entityState.isUnchanged()).toBe(true); // OK
Is this expected behavior? And if not how I can fix it?

Related

How do you define parentName, parentId, and connectionName in getConfigs for a nested connection?

I am running into some issues writing a Relay Mutation on a nested connection. Here is the type structure:
{
viewer {
entity(id) {
events // mutate connection here
}
}
}
In the getConfigs I have both the parentName and parentID pointing to the "viewer", however the connectionName "events" does not exist on the viewer it exists on the "entity" type.
As you will see in the code snippet below I am also unsure how to use variables in the getFatQuery to fetch the mutated data with an entity ID.
getConfigs and getFatQuery:
getConfigs() {
return [{
type: 'RANGE_ADD',
parentName: 'viewer',
parentID: this.props.viewer.id,
connectionName: 'events',
edgeName: 'eventEdge',
rangeBehaviors: {
'': 'append'
},
}];
}
getFatQuery() {
return Relay.QL`
fragment on addEventPayload {
viewer {
entity(id: $entityId) // how do I use variables in the getFatQuery {
events(first: 20) {
edges {
node {
status
}
}
}
}
},
eventEdge
}
`;
}
I am more than happy to help clarify my question if it makes no sense so please feel free to ask questions about my question.
Thanks for the help!
For anyone in the future getting snagged on this you don't have to worry about passing in the id again or dealing with nested queries/fields. Relay will just find and update the appropriate record on the client. This issue on Github was helpful for figuring this out, especially the comments from freiksenet.
In the example above - Instead of going through the viewer we just go straight to the entity.
outputFields:
outputFields: {
eventEdge: {
type: eventEdge,
resolve: async({event}) => {
const eventsByOwner = await Event.getEventsByOwnerId(event.ownerId)
const eventIndex = eventsByOwner.findIndex(evt => evt.id == event.id);
const cursor = offsetToCursor(eventIndex);
return {
cursor: cursor,
node: event
};
}
},
entity: {
type: entity,
resolve: async({event}) => {
return Entity.getEntity(event.ownerId)
}
},
}
getConfigs and getFatQuery:
getConfigs() {
return [{
type: 'RANGE_ADD',
parentName: 'entity',
parentID: this.props.entityId,
connectionName: 'events',
edgeName: 'eventEdge',
rangeBehaviors: {
'': 'append'
},
}];
}
getFatQuery() {
return Relay.QL`
fragment on addEventPayload #relay(pattern: true) {
entity {
events
},
eventEdge
}
`;
}
Note: Using #relay(pattern: true) will make sure you don't run into issues when you don't pass in arguments for connection queries and will fall back to your last query of this type.

Angularjs ui-grid events not removed per row after data update

I have a grid that contains an edit button per each row. Everything works as expected the first time the page is loaded, but if I try to add a new entity and repopulate the grid, the edit button will fire the edit event of the first already existing entity.
This is my code:
var columnDefs = [
{
name: '', field: 'id',
cellTooltip: 'Edit',
enableSorting: false,
enableColumnMenu: false,
enableCellEdit: false,
maxWidth: 30,
headerCellTemplate: '<div class="ui-grid-cell-contents ui-grid-icon"></div>',
cellEditableCondition: false,
cellTemplate: '<div class="ui-grid-cell-contents ui-grid-icon"><div title="Edit" class="ui-edit ui-grid-icon-pencil" ng-click="grid.appScope.editNews({{row.entity.id}})"></div></div>'
},
{ name: 'shortDescription', field: 'shortDescription' }];
$scope.gridOptions = {
enableGridMenu: false,
enableSorting: false,
enableRowHashing: false,
columnDefs: columnDefs,
data: "data",
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
}
};
var getData = function () {
showLoading('.grid');
newsRepository.resourceFunctions.query(displayOptions,
function (data) {
if (data.length == 0) {
setEmptyGrid($scope, 'There are no news!');
$scope.data = [{
"message": 'There are no news!'
}];
}
else {
setGrid(data);
}
hideLoading('.grid');
}, //success
function (error) {
$scope.gridApi.selection.clearSelectedRows();
hideLoading("#view-container");
toaster.pop('error', "Server error",
"There was an error while processing your request. Please contact support.", 10000);
}); //error
};
function setGrid(data) {
$scope.gridOptions.columnDefs = columnDefs;
$scope.data = data;
}
This is how the grid is re-populated (the data is comming from the save AJAX request):
$scope.gridApi.selection.clearSelectedRows();
setGrid(data.items);
The edit event is inside the cellTemplate: grid.appScope.editNews({{row.entity.id}}). Also, after the grid data is updated, this template is populated with the correct entity id, but the editNews is called with the id of the older entity. Any ideas how I can fix this?
I had a similar problem to this today, although more to do with cellTemplate buttons not shifting to their correct row when a new row was added, or an existing row removed.
In your particular case just remove the {{ and }} in your call to editNews. E.g. it should be:
ng-click="grid.appScope.editNews(row.entity.id)". This worked nicely for me.

how to implement mutation responses on a local falcor Model dataset

Given that I have an example Model:
var model = new falcor.Model({
cache: {
userById: {
"1": {
name: "User",
email: "user#email.com"
}
},
users: {
current: null
}
}
});
This is a local model that I'm using for testing purposes, and I would like to implement it on a call to users.login so the user so that I can call:
model.call(['users', 'login'], ['user', 'password'])
I realized that if I do this:
var model = new falcor.Model({
cache: {
userById: {
"1": {
name: "User",
email: "user#email.com"
}
},
users: {
current: null,
login: function(user, password) {
console.log('this code is reached', user, password);
// what to return in order to mutate model?
}
},
}
});
When I do the call it gets there, but I can't figure out how to mutate the model as part of the response; on the server side we return the paths with values and invalidates, and it just works, but here I tried:
// trying returning as a jsonGraph response, don't work
login: function() {
return {
jsonGraph: {
users: {
current: {$type: "ref", value: ['userById', '1']}
}
},
paths: [['users', 'current']]
}
}
// trying returning as a path set mutation list, don't work
login: function() {
return [{path: ['users', 'current'], value: {$type: "ref", value: ['userById', '1']}}]
}
// trying force call to set on the model, don't work
login: function() {
this.set([
{path: ['users', 'current'], value: {$type: "ref", value: ['userById', '1']}}
])
}
// trying using ModelResponse, got an example on some external sources, don't work
login: funtion() {
return new ModelResponse((observer) => {
observer.onNext({
jsonGraph: {
users: {
current: {$type: "ref", value: ['userById', '1']}
}
},
paths: [['users', 'current']]
});
observer.onCompleted();
});
}
Now I don't know what else to try; I need a simple way to declare mutations after a call into a local model, if you know how to solve this, please let me know here.
Thanks.
The client model cache only supports JSONGraph, which b/c it is essentially just JSON with some conventions, doesn't support functions. So, when working with a falcor model cache and no dataSource/middle tier router, it is not possible to implement calls.
This can be kind of annoying when prototyping/testing, as a router is conceptually more difficult than a simple JSON cache object. I ran into this a while ago, so I wrote a dataSource module to support it: falcor-local-datasource. The dataSource is initialized with a graph object that does support function nodes, and as with your above examples, will mutate the graph based on the function's returned JSONGraphEnvelope or an array of PathValues.

How to initialize the selection for rails-select2 in BackboneForms schema?

The project uses marionette-rails, backbone-on-rails, select2-rails and this port to BackboneForms to provide a multiselect form field. The select options are available to the user. They are retrieved from the collection containing the total list of options:
MyApp.module("Products", function(Products, App, Backbone, Marionette, $, _) {
Products.CustomFormView = Products.CustomView.extend({
initialize: function(options) {
this.model.set("type", "Product");
Products.EntryView.prototype.initialize.apply(this, arguments);
},
schemata: function() {
var products = this.collection.byType("Product");
var productTypes = products.map(function(product){
return {
val: product.id,
label: product.get("name")
};
});
return {
productBasics: {
name: {
type: "Text",
title: "Name",
editorAttrs: {
maxLength: 60,
}
},
type: {
type: 'Select2',
title: "Product type",
options: {
values: productTypes,
value: [3, 5],
initSelection: function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
}
},
editorAttrs: {
'multiple': 'multiple'
}
}
}
};
}
});
});
Do I initialize the value correctly in options.value? How comes initSelection is never called? I copied the function from the documentation - it might be incomplete for my case. None of the products with the IDs 3 and 5 is displayed as the selection.
initSelection is only used when data is loaded asynchronously. My understanding is that there is no way of specifying the selection upon initialization if you are using an array as the data source for a Select2 control.
The best way of initializing the selection is by using setValue after the form is created. Here is a simplified example based on the code in your example.
var ProductForm = Backbone.Form.extend({
schema: {
type: {
type: 'Select2',
title: "Product type",
options: {
values: productTypes,
},
editorAttrs: {
'multiple': 'multiple'
}
}
});
var form = new ProductForm({
model: new Product()
}).render();
form.setValue("type", [3, 5]);
You can use value function (http://ivaynberg.github.io/select2/#documentation) in setValue. I personally recomend you to use this backbonme-forms plugin: https://gist.github.com/powmedia/5161061
There is a thread about custom editors: https://github.com/powmedia/backbone-forms/issues/144

kendo ui Combobox binded to a Grid losts it's value and text after Grid's Cancel button pressed

I have two views in database. Bonuses and employees. One(employee)-to-many(bonuses).
I have kendo ui grid (kendo web), which displays ajax results from controller called Bonuses
And an autocompliting element - Employee Combobox binded with Employee filed of a grid.
Grid's datasource:
// bind json result from /Bonuses/GetPagedJsonBonuses
var bonusesDataSource = new kendo.data.DataSource({
transport: {
read: "#Url.Action("GetPagedJsonBonuses", "Bonuses")",
update: {
url: "#Url.Action("Edit", "Bonuses")",
type: "PUT"
},
create: {
url: "#Url.Action("Create", "Bonuses")",
type: "POST"
},
parameterMap: function(options, operation) {
if (operation === "update" || operation === "create") {
// updates the BonusDTO.EmployeeId with selected value
if (newValueEmployeeId !== undefined)
options.EmployeeId = newValueEmployeeId;
}
return options;
}
},
schema: {
data: "Data", // PagedResponse.Data
total: "TotalCount", // PagedResponse.TotalCount
model: {
id: "BonusId", // Data
fields: {
EmployeeId: { type: "number" },
EmployeeLastName: {
type: "string",
editable: true,
//validation: { required: {message: "Employee's last name is required"}}
},
Amount: {
type: "number",
editable: true,
nullable: false,
validation: {
required: { message: "Amount is required to be set" }
}
}
} // fields
} // model
}// schema
});
Grid element looks like this:
// creates bonuses grid control
$("#bonusesGrid").kendoGrid({
dataSource: bonusesDataSource,
toolbar: ["create"],
editable: "inline",
columns: [
"BonusId",
"EmployeeId",
{
field: "EmployeeLastName",
editor: employeeAutocompletingEditor,
template: "#=EmployeeLastName#"
},
"Amount",
{
command: ["edit"],
title: " "
}
],
save: function(e) {
if (newValueEmployeeId !== undefined && newValueEmployeeLastName !== undefined) {
e.model.EmployeeId = newValueEmployeeId; // it's a hack to bind model and autocomplete control
e.model.EmployeeLastName = newValueEmployeeLastName;
}
},
edit: function(e) {
setCurrentValueEmployeeIdAndLastName(e.model.EmployeeId, e.model.EmployeeLastName);
},
cancel: function(e) {
setCurrentValueEmployeeIdAndLastName(e.model.EmployeeId, e.model.EmployeeLastName);
}
});
Autocompleting combobox has it's own datasource using ajax:
// datasource for autocomlete combobox to lookup employees names from
var employeesDataSource = new kendo.data.DataSource({
transport: {
read: "#Url.Action("GetJsonEmployeesByLastName", "Bonuses")",
},
parameterMap: function(options, operation) {
if (operation === "update" || operation === "create") {
setNewValueEmployeeIdAndLastName(options.Id, options.LastName);
}
return options;
},
});
Autocompliting combobox look's like this:
function employeeAutocompletingEditor(container, options) {
$('<input required data-text-field="LastName" data-value-field="EmployeeId" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoComboBox({
// sets the local variables to update values of current row.
change: function() {
setNewValueEmployeeIdAndLastName(this.value(), this.text());
},
dataBinding: function (e) {
console.log("dataBinding: ", e, this.dataItem());
},
dataBound: function (e) {
console.log("dataBound: ", e, this.dataItem());
},
dataSource: employeesDataSource
});
}
I use Editor binding to pass values(EmployeeId) and Text (EmployeeLastName) from grid to combobox.
I also use a hack like temporal variables (newValueEmployeeId, currentValueEmployeeId) to
send selected Employee in combobox and pass it to grid for correct save. A found it's a most common practice to pass a value back to grid.
My problems is:
If I press Edit button on my grid first time The combobox displays current employee's name from grid row:
If I press Cancel button and again press Edit button, combobox doesn't display current value of grid (employee's name)
IF I type some name, change some other values, and Udate(save) value, next time combobox again displays employees name, but only once before Cancel was pressed.
I'm very new in Kendo UI and this problem drives me crazy...
I think that combobox losts it's binding or doesn't update smth. I tried to set values while onBound and onBinding events, but this doesn't help. Please help me with an advice and example.
PS all evenets and functions is my try to debug and find solution.
only one fix helped me:
var employeeList = new List<Employee>()
employeeList.add(new Emplpyee()) // add fake employee record.
return Json(employeeList)
I don't know why, but grid control start make cyclying empty ajax requests if I return empty list of employees or null. This doesn't work:
return Json(new List<Employee>());
return Json(null);
I think it's a problem in kendo combobox itself ,because it's not ready to receive and handle empty list or null as json result.
Also I heared something, that JQuery doesn't support empty or null results anymore...maybe that's the reason

Resources