Subscribing to valueChanges for multiple fields is causing performance issue in reactive form angular 2 - angular-reactive-forms

I have more than 50 fields those are input text and dropdowns in the reactive form. The fields are dependent to each other's value changes in order to trigger validation and to display related field after the selection.
I subscribed to the value changes in ngOnInit() as below:
ngOnInit() {
this.setPageValidation();
}
setPageValidation() {
this.NameSubscription = this.FormGroup.get('personnel').get('name').valueChanges.subscribe(data
=> {
this.enableOrders();
});
this.StateSubscription = this.FormGroup.get('personnel').get('state').valueChanges.subscribe(data
=>
{
this.enableAccount();
});
// more value changes subscription like 40 fields ............................
}
While loading the form, it is taking longer time to load due to subscribing for the value changes when the form loads.
I tried implementing it to move the code to ngOnChanges() but it is not triggering the enable and display of other fields depending on it's initial value that are filled from the table if there are values for those fields. It is just populating the first field and the rest does not display depending upon on its value.
I would like to thank you in advance. I really appreciate your help if there is any best approach to it to resolve without performance issue.

You can do with a single subscription.
this.personnelSubscription =
this.Formgroup.get('personnel').valueChanges.subscribe(data => {
if (data) {
//Console log the data here. It will print the formGroup of personnel
// then select the control and add your validations
// like this data.controls.state
}
})

Related

Apollo client: Making optimistic updates while creation is still in progress

I want to be able to do updates on an object while it is still being created.
For example: Say I have a to-do list where I can add items with names. I also want to be able to edit names of items.
Now say a user with a slow connection creates an item. In that case I fire off a create item mutation and optimistically update my UI. That works great. So far no problem
Now let's say the create item mutation is taking a bit of time due to a slow network. In that time, the user decides to edit the name of the item they just created. For an ideal experience:
The UI should immediately update with the new name
The new name should eventually be persisted in the server
I can achieve #2 by waiting for the create mutation to finish (so that I can get the item ID), then making an update name mutation. But that means parts of my UI will remain unchanged until the create item mutation returns and the optimistic response of the update name mutation kicks in. This means #1 won't be achieved.
So I'm wondering how can I achieve both #1 and #2 using Apollo client.
Note: I don't want to add spinners or disable editing. I want the app to feel responsive even with a slow connection.
If you have access to the server you can implement upsert operations, and you can reduce all queries to the such one:
mutation {
upsertTodoItem(
where: {
key: $itemKey # Some unique key generated on client
}
update: {
listId: $listId
text: $itemText
}
create: {
key: $itemKey
listId: $listId
text: $itemText
}
) {
id
key
}
}
So you will have a sequence of identical mutations differing only in variables. An optimistic response accordingly, can be configured to this one mutation. On the server you need to check if an item with such a key already exists and create or update an item respectively.
Additionally you might want to use apollo-link-debounce to reduce number of requests when user is typing.
I think the easiest way to achieve your desired effect is to actually drop optimistic updates in favor of managing the component state yourself. I don't have the bandwidth at the moment to write out a complete example, but your basic component structure would look like this:
<ApolloConsumer>
{(client) => (
<Mutation mutation={CREATE_MUTATION}>
{(create) => (
<Mutation mutation={EDIT_MUTATION}>
{(edit) => (
<Form />
)}
</Mutation>
)}
</Mutation>
)}
</ApolloConsumer>
Let's assume we're dealing with just a single field -- name. Your Form component would start out with an initial state of
{ name: '', created: null, updates: null }
Upon submitting, the Form would do something like:
onCreate () {
this.props.create({ variables: { name: this.state.name } })
.then(({ data, errors }) => {
// handle errors whichever way
this.setState({ created: data.created })
if (this.state.updates) {
const id = data.created.id
this.props.update({ variables: { ...this.state.updates, id } })
}
})
.catch(errorHandler)
}
Then the edit logic looks something like this:
onEdit () {
if (this.state.created) {
const id = this.state.created.id
this.props.update({ variables: { name: this.state.name, id } })
.then(({ data, errors }) => {
this.setState({ updates: null })
})
.catch(errorHandler)
} else {
this.setState({ updates: { name: this.state.name } })
}
}
In effect, your edit mutation is either triggered immediately when the user submits (since we got a response back from our create mutation already)... or the changes the user makes are persisted and then sent once the create mutation completes.
That's a very rough example, but should give you some idea on how to handle this sort of scenario. The biggest downside is that there's potential for your component state to get out of sync with the cache -- you'll need to ensure you handle errors properly to prevent that.
That also means if you want to use this form for just edits, you'll need to fetch the data out of the cache and then use that to populate your initial state (i.e. this.state.created in the example above). You can use the Query component for that, just make sure you don't render the actual Form component until you have the data prop provided by the Query component.

redux-form initialize FieldArray

I'm trying to create a redux form which integrates many aspects of redux-form.
To give a better introduction to the project I would like to share the main goals with you.
At the moment i've a dynamic form which can be extended with participants. Each participant has a superior. On user input (Async.Creatable React select) I request (call to API) all users based on the text. To sum up, an Autosuggestion. When receiving the users I make a second call to get the corresponding superior. Afterwards I would like to autofill the fields for the participant as well as for the superior.
Everything works quite well for the first participant + superior. Unlike the first participant the second superior is not getting autofilled.
Is it required to call the initialize action (redux-form) manual, when mutating the initalValues Property?
The function getFormData access the current state. These state is as expected and contains the following data.
These state is created with the LOAD action of redux-form
initial
:
attendees
:
Array(2) <-- Autofilled fields [{name: FirstTest, firstName: FirstTest}, {name: SecondTest, firstName: SecondTest}]
const mapStateToProps = (state) => {
const attendeesFromFormData = getFormData(state, REGISTRATION_FORM, [{}]).attendees
const attendees = attendeesFromFormData ? attendeesFromFormData : [{}]
return {
initialValues: {
attendees: attendees
}
}
}
export default connect(mapStateToProps, {searchADUser, autoFillAttendee, getADUser})(reduxForm({
form: REGISTRATION_FORM,
enableReinitialize: true
})(RegistrationForm))
Okay after a bit research and testing I find a simple solution for my problem.
Each time you add a participant you have to initialize manually the redux-form.

Eclipse scout neon import form data in abstract box on field change

I have abstract group box. Inside this group box I have smart field, and on change I would like to fill some other fields in form.
Problems are :
on abstract group box new box form data can't be created.
if I try to import form data, because import form data called setValue loop is detected.
My try was to change abstract group box to "normal group box" and set values like this :
#Override
protected void execChangedValue() {
AbstractCarSelectionBoxData formData = new AbstractCarSelectionBoxData();
FormDataUtility.exportFormData(this.getParentField(), formData);
formData = BEANS.get(IOfferFormService.class).loadCarInformations(formData);
FormDataUtility.importFormFieldData(this.getParentField(), formData, false, null, null);
}
This approach actually work, and fill the data, but I get
2016-03-22 10:18:57,448 WARN scout-model-thread-20 o.e.s.rt.client.ui.form.fields.AbstractValueField - Loop detection in com.sixt.leasing.scout.client.template.AbstractCarBox$CarTypeSixtField with value 279096 [m4042 # ]
java.lang.Exception: null
at org.eclipse.scout.rt.client.ui.form.fields.AbstractValueField.setValue(AbstractValueField.java:324) [org.eclipse.scout.rt.client-5.2.0.M5.jar:5.2.0.M5]
at org.eclipse.scout.rt.client.ui.form.fields.AbstractValueField.importFormFieldData(AbstractValueField.java:219) [org.eclipse.scout.rt.client-5.2.0.M5.jar:5.2.0.M5]
What is right approach to deal with this case?
I know that I could always get only the DTO object and set values in client, but this is not what I would like to have...
Solution for problem 1
Create an abstract method AbstractCarSelectionBoxData createNewBoxData();
in AbstractCarSelectionBox and implement it in the corresponding subclasses returning the new form data, e.g. new MyFormDataContainingCarSelectionBox().getCarSelectionBox();.
Solution for problem 2
Before importing the form data, call setValueSet(false) on the field that triggered the execChangedValue, e.g. formData.getMySmartfield().setValueSet(false).
This will make sure that it's not imported into the form, thus no loop detection should occur.
I think the importFormFieldData on this.getParentField() triggers the execChangedValue on the smart field again.
Try to box updated fields in a own group box and import the data only in this group box or do de import manually on each field you want to update.

In Meteor, where do I model my business rules?

Beginner question : I've worked through the Try Meteor tutorial. I've got fields in my HTML doc, backed by helper functions that reference collections, and BOOM --> the fields are updated when the data changes in the DB.
With the "Hide completed" checkbox, I've also seen data-binding to a session variable. The state of the checkbox is stored in the Session object by an event handler and BOOM --> the list view is updated "automatically" by its helper when this value changes. It seems a little odd to be assigning to a session object in a single page application.
Through all this, my js assigns nothing in global scope, I've created no objects, and I've mostly seen just pipeline code, getting values from one spot to another. The little conditional logic is sprayed about wherever it is needed.
THE QUESTION... Now I want to construct a model of my business data in javascript, modelling my business rules, and then bind html fields to this model. For example, I want to model a user, giving it an isVeryBusy property, and a rule that sets isVeryBusy=true if noTasks > 5. I want the property and the rule to be isolated in a "pure" business object, away from helpers, events, and the meteor user object. I want these business objects available everywhere, so I could make a restriction, say, to not assign tasks to users who are very busy, enforced on the server. I might also want a display rule to only display the first 100 chars of other peoples tasks if a user isVeryBusy. Where is the right place to create this user object, and how do I bind to it from my HTML?
You can (and probably should) use any package which allows you to attach a Schema to your models.
Have a look at:
https://github.com/aldeed/meteor-collection2
https://github.com/aldeed/meteor-simple-schema
By using a schema you can define fields, which are calculated based on other fields, see the autoValue property: https://github.com/aldeed/meteor-collection2#autovalue
Then you can do something like this:
// Schema definition of User
{
...,
isVeryBusy: {
type: Boolean,
autoValue: function() {
return this.tasks.length > 5;
}
},
...
}
For all your basic questions, I can strongly recommend to read the DiscoverMeteor Book (https://www.discovermeteor.com/). You can read it in like 1-2 days and it will explain all those basic questions in a really comprehensible way.
Best Regards,
There is a very good package to implement the solution you are looking for. It is created by David Burles and it's called "meteor-collection-helper". Here it the atmosphere link:
You should check the link to see the examples presented there but according to the description you could implement some of the functionality you mentioned like this:
// Define the collections
Clients = new Mongo.Collection('clients');
Tasks = new Mongo.Collection('tasks');
// Define the Clients collection helpers
Clients.helpers({
isVeryBusy: function(){
return this.tasks.length > 5;
}
});
// Now we can call it either on the client or on the server
if (Meteor.isClient){
var client = Clients.findOne({_id: 123});
if ( client.isVeryBusy() ) runSomeCode();
}
// Of course you can use them inside a Meteor Method.
Meteor.methods({
addTaskToClient: function(id, task){
var client = Clients.findOne({_id: id});
if (!client.isVeryBusy()){
task._client = id;
Tasks.insert(task, function(err, _id){
Clients.update({_id: client._id}, { $addToSet: { tasks: _id } });
});
}
}
});
// You can also refer to other collections inside the helpers
Tasks.helpers({
client: function(){
return Clients.findOne({_id: this._client});
}
});
You can see that inside the helper the context is the document transformed with all the methods you provided. Since Collections are ussually available to both the client and the server, you can access this functionality everywhere.
I hope this helps.

jqGrid saving a row with nullable columns

So I have a jqGrid on an ASP.NET MVC 3 website. It's loading the data, searching, filtering, and saving rows with the built in pop-up editor. What I can't get to work is saving a nullable property. I'm using LargeJsonResult instead of the built in JsonResult, so an example of a row in the grid is this:
// C# class
public class Row
{
public string A { get; set; }
public string B { get; set; }
public int C { get; set; }
}
// an example object instance, let's say these values come from the DB
var ret = new Row { A = "a", B = null, C = 5 };
// the JSON string sent to the grid will look like this (notice B is omitted)
// "{ A: 'a', C: 5 }"
Now, the grid will show this as:
A B C
a undefined 5
And this brings me to my problem. The pop-up edit form will show "undefined" in the textbox for B, and will also post this to the server. So if I save that to the database, I'll have "undefined" in my DB instead of null.
How do I get jqGrid to preserve the null value round trip? One solution that seems to me very hacky is based on something Oleg solved in another thread:
// override jqGrid serialization
jQuery.extend(jQuery.jgrid.edit, { ajaxEditOptions: { contentType: "application/json" }, serializeEditData: function (data) {
return JSON.stringify(data).replace(/"undefined"/g, 'null');
}});
This will work, but seems dangerous because it's doing mass edits of data without the user's knowledge. In thinking more about it, I guess this is the fundamental problem of saving back null instead of "undefined" or some other string representation of null (empty string, etc.). The desired behavior would be:
if the property is null, and the user doesn't change the value, it posts as null
if the user changes the value, the property is no longer null
Can we get the grid's edit form to behave like this for nullable properties? Or would I have to create a custom edit form that tracks what the user does with a property?
I hope that I understand your problem. In one my applications where I used jqGrid I had once the problem with NULL values. At the time of development of the application I was not sure how to solve the problem and I placed on the server side the text value "(NULL)" instead of null value of one property. The grid was for advanced users who understand what "(NULL)" is. The value "(NULL)" has no sense in the field (one had no user account with the name) and inside of server code for the Edit operation I could distinguish "(NULL)" value from the real field value. In the way I could come over the problem.
In your case you should solve at least two problems:
You should decide how the null value should be displayed. The "undefined" text seems me not the best one. You can solve the problem with the "undefined" text either on the server side (like I did in my case) or with respect of custom formatter. The custom formatter is very simple thing. It define how a cell value should be displayed as a HTML fragment of the <td> contain. You can for example include an additional hidden <span> element or other HTML element or attribute which will save the information that the value was null.
You should solve the problem with decoding of the null value on the server side during Edit operations. You can solve the problem very easy on the server side (like I do with compare of the corresponding field to the "(NULL)") or with respect of custom unformatter on the client side. The custom unformatter will get the information from the grid cell (from the hidden <span> or other hidden HTML element or attribute) and place the information in the server request.
You can look at the demo for the answer to see an example how one can use a hidden <span> to save an additional information in the cell with respect of custom formatter and to read the information later with respect of custom unformatter.

Resources