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

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.

Related

Spring boot + JPA(Hibernate) Edit partial entity fields

all.
I have following simple form in which I want to edit the entity. The problem is that I have some fields which I don't want to be edited. For example (Image file path).
As it is now, I have the service method -
public void addOrModifyLayout(Layout layout){
if(layout.getId() == null){
layoutRepository.save(layout);
}
else {
Layout modifiedLayout = new Layout();
modifiedLayout.setId(layout.getId());
modifiedLayout.setName(layout.getName());
modifiedLayout.setStatus(layout.getStatus());
modifiedLayout.setExhibitor(layout.getExhibitor());
layoutRepository.save(modifiedLayout);
}
}
As you can see, every field that I want to be able to be edited, I should explicitly put it in the service. Can I use some mapper or trick to update only some fields that are in the view (form) ? How you handle this kind of issues?
You can either
store all the entity fields in hidden inputs (e.g. imageFilePath hidden input). So you can store on UI all the entity fields and get them back to assign to the entity.
OR
Avoid new entity creation but retrieve existing one and fill only necessary fields.
Layout modifiedLayout = layoutRepository.getById(layout.getId());
modifiedLayout.setName(layout.getName());
modifiedLayout.setStatus(layout.getStatus());
modifiedLayout.setExhibitor(layout.getExhibitor());
layoutRepository.save(modifiedLayout);

Grail validate data already saved to database

I have this really complicated form. All the fields must be filled, but the process of filling can be saved and leter continued. So what i need s that when finally confirm is pressed, all the data get validated. But because it is already saved to database calling validate() wont work. I save the data by douing save(validate:false), because i dont need validation when the work is still in progremm.
How can i validate data that has already been saved to database ? Do i have to do it manually?
What happens when you validate an already persisted object?
Is there a way to make it appear dirty after retrieving and before validating?
I have edited the answer to explain form encapsulation in more detail, typically maybe from a tier step process of form input or more complex iterated objects that needs to be elsewhere. To begin if all you need is a one step that captures a variety of information and you are happy to then process all that manually and store in different classes on mass params dump then look into jquery-ui tabs. If you choose to use the dynamic feature of tabs i.e. <li><a href="someurl">click</li> which then loads content dynamically to a given tab then that would also cover single forms that are outside or maybe if you prefer more complex within DOM.
Anyhow the reason for my edit wasn't above it is for something a little more complex that captures multi tier forms.
So you had step 1 that sent params through to a controller that then passed those params to a new gsp or maybe even an iteration of something that belongs to another totally different object within the form.
Typically you would end up with:
<g:form action=myDomain" action="doThis">
<!-- this is some iteration that belongs to some other class outside of what i am actually trying to do: -->
<g:each in="someObject" var="p">
<g:hiddenField name="form1.firstName" value="${p.firstName}"/>
<!-- in this case hidden -->
<g:hiddenField name="form1.surName" value="${p.surName}"/>
</g:each>
<!-- this is my actual form -->
<g:textField name="username" />
</g:form>
When form is submitted to a controller
Class MyDomainController {
def doThis(MyBean bean) {
save(bean)
}
}
//this be in src/main/groovy
import grails.validation.Validateable
//important for some reason it needs entire collections
// have had issues initialising it without .*
import org.apache.commons.collections.*
Class MyBean implements Validateable {
//this is capturing the current form fields
String username
//This is now collecting our form1 fields
List<MyDetailsBean> form1 = ListUtils.lazyList([], { new MyDetailsBean() } as Factory)
//if that had been 1 instance of it or like as mentioned passed from pervious form and called form2
MyDetailsBean form2
static constraints={
username(nullable:false) //, validator: checkSomething)
}
}
This is again in src/main/groovy and was used to originally collect each iteration of an object:
import grails.validation.Validateable
Class MyDetailsBean implements Validateable {
String firstName
String surName
}
I have updated the answer since i suggested encapsulating the object in a bean without any details of how one would go about doing such a thing. I hope above is clear. It is all on the fly but if tested hope it all works as explained above.
TO add after next update explained form2 example. to finally validate both sets you call
if (bean.validate() && bean.form2.validate()) {
//all good
}
Because you are binding it to another validation class the rules of that class can now be applied as part of validation process.
Old answer
Quite simply put it is on the db why on earth would you want to validate a validated input. Anyhow the work around is a validation bean in Grails 2 src/groovy/package which is #Validateable or
Grails 3 : src/main/groovy/package which implements Validateable
class MyDmainBean {
// must declare id
def id
// Then each object in your real domain class
static constraints = {
id (nullable:true,bindable:true)
importFrom MyDomainClass//, exclude: ['field1']
//field 1 is not included but if field 1 was integer
// in actual domain class and BigDecimal in bean
//then exlude it since it won't bind
}
def formatObject(MyDomainClass domain) {
id=domain.id
..
}
}
Now you can call
MyDomain record = MyDomain.get(0L)
MyDmainBean bean = new MyDmainBean().formatObject(record)
bean.validate()

How to manage new Breeze entities which are aggregate roots?

I have a domain model which has a Customer, which in turn has 1 Address (1:1) and 1 or more Phone numers (1:M).
Customer has user supplied PK (a string), while Address and Phone use identity column (server generated).
I am struggling in trying to understand how to manage Breeze entity creation for a "Add new Customer" screen.
The form on the screen allows user to enter Customer, Address, and Phone data.
I am using Durandal and Knockout so my "customeradd.js" viewmodel looks something like this:
// -- snip ---
var customer = ko.observable(),
hasChanges = ko.computed(function () {
return datacontext.hasChanges();
});
var vm = {
hasChanges: hasChanges,
customer: customer,
activate: activate
};
return vm;
function activate() {
customer(datacontext.createCustomer());
}
// -- snip ---
and my "/services/datacontext.js" :
// -- snip ---
breeze.NamingConvention.camelCase.setAsDefault();
var manager = new breeze.EntityManager(config.remoteServiceName);
var hasChanges = ko.observable(false);
manager.hasChangesChanged.subscribe(function (eventArgs) {
hasChanges(eventArgs.hasChanges);
});
function createVehicle() {
return manager.createEntity("Customer");
}
// -- snip ---
My questions are following:
Once I create a Customer, do I need to create Address and list of Phones and add them to Customer entity before making it a KO observable? Or is this done automatically by createEntity() method?
How do I create a Customer but without having to specify the Id? If I set the key to null or '', Breeze complains ("Error: Cannot attach an object to an EntityManager without first setting its key or setting its entityType 'AutoGeneratedKeyType' property to something other than 'None'"). However, if I generate the temp key (using either breeze.core.getUuid() or something else), then it shows up in my Id form field, and I really want the end user to specify it....Do I have to resort to extending the entity with extra field and then do the swapping and validation before saving (I don't like this idea at all)? Is there a better way?
In order to enable/disable buttons on my form I am tracking if there are changes in EntityManager. But every time entity is created, it is automatically in 'added' state so hasChanges is true. What I want is for changes to be picked up only if user edits the form (and therefore makes changes to underlaying entity). What is the best way to approach this?
BTW, I have seen this recommendation to register custom constructor for entity (I have already implemented it but I am still not clear how to let user supply their own id and to flag entity as modified only when user edits it...)
I realize this has been up for a while, but here are my thoughts (in case anyone comes looking).
If you use the entityManager to create your customerl and everything is specified correctly in the metadata, you can just create the customer and add phone numbers/addresses as needed. Breeze automatically makes an entity's properties observable (if specified correctly and if breeze knows that KO is being used)
If you can only do it the way that you say, then you are stuck. Ideally, you would have a user-entered ID which is NOT the key (though you could still force it to be unique) and a database-generated key, which Breeze will manage behind the scenes (assigning a negative key until it is saved to the data store, then updating the key and all related keys without any input from you).
if you use the 2nd approach for answer 2, then your buttons can easily be enabled and disabled using ko data-binding. When you create the entity, save its value to the viewmodel (custSource). Then you can add to the save button the data-bind="disable: custSource == Customer(), enable: custSource != Customer()". (You might need to play around with the syntax -- I haven't tested that part yet)
I don't think you need a custom constructor unless you are doing something different from what I understand.
PS. you should be aware that I believe Breeze wants Knockout defined as 'ko', while Durandal definitely expects it to be 'knockout', so you will probably need a 'map' property in your require.config
I think you could solve some of your problems by taking a slightly different approach to your entity creation. Here's your current approach:
Create a customer entity
User modifies that entity
Save the changes
Instead, try this:
User enters customer information
Create and save the customer entity
I realize that this doesn't really answer your questions, but I've found the second approach to be much easier to implement. Just have the user enter all the information you need to create a customer, and then supply those values to createEntity.
customeradd.js
// -- snip ---
var vm = {
customerId: ko.observable(),
address: ko.observable(""),
phoneNumbers: ko.observableArray([]),
submit: submit
};
return vm;
function submit() {
datacontext.createCustomer(
vm.customerId(),
vm.address(),
vm.phoneNumbers());
}
// -- snip ---
/services/datacontext.js
// -- snip ---
/**
* Creates a new customer.
* #param {int} id - The customer's id number.
* #param {string} address - The customer's address.
* #param {string[]} phoneNumbers - An array of the customer's phone numbers.
*/
function createCustomer(id, address, phoneNumbers) {
return manager.createEntity("Customer",
{
id: id,
address: address,
phoneNumber: phoneNumbers
});
}
// -- snip ---

Knockout Mapping - Fill Observable Arrays keeping Items' methods

I've been facing a problem that is basically the following:
I have a knockout ViewModel which contains observable arrays of items with observable properties and methods.
I need to pull data from the server. The methods need to exist after data is taken from server. So I create a new ViewModel and then update its value from what comes from server. (THIS DOES NOT WORK, THE RESULTING ARRAY HAS NO ITEMS)
If I create, with mapping, a new object using var newObj = ko.mapping.fromJS(data) the resulting Array has items, but its items have no methods. It spoils my Bindings.
The fiddle of my problem: http://jsfiddle.net/claykaboom/R823a/3/ ( It works util you click in "Load Data From The Server" )
The final question is: What is the best way to have items on the final array without making the loading process too cumbersome, such as iterating through every item and filling item's properties in order to keep the previously declared methods?
Thanks,
I changed your code little bit. Check this version of JSFiddle.
var jsonFromServer = '{"ModuleId":1,"Metadatas":[{"Id":1,"MinValue":null,"MaxValue":null,"FieldName":"Teste","SelectedType":"String","SelectedOptionType":null,"IsRequired":true,"Options":[]}]}';
Your code doesnt work because your jsonFromServer variable does not contain methods we need at binding like you described in your question. ( -- > Metadatas )
So we need to define a custom create function for Metadata objects at the mapping process like this :
var mapping = {
'Metadatas': {
create: function(options) {
var newMetaData = new MetadataViewModel(options.parent);
newMetaData.Id(options.data.id);
newMetaData.FieldName(options.data.FieldName);
newMetaData.SelectedType(options.data.SelectedType);
newMetaData.SelectedOptionType(options.data.SelectedOptionType);
newMetaData.IsRequired(options.data.IsRequired);
newMetaData.Options(options.data.Options);
// You can get current viewModel instance via options.parent
// console.log(options.parent);
return newMetaData;
}
}
}
Then i changed your load function to this :
self.LoadDataFromServer = function() {
var jsonFromServer = '{"ModuleId":1,"Metadatas":[{"Id":1,"MinValue":null,"MaxValue":null,"FieldName":"Teste","SelectedType":"String","SelectedOptionType":null,"IsRequired":true,"Options":[]}]}';
ko.mapping.fromJSON(jsonFromServer, mapping, self);
}
You dont have to declare a new viewModel and call ko.applyBindings again. Assigning the updated mapping to current viewModel is enough. For more information check this link. Look out for customizing object construction part.
The final question is: What is the best way to have items on the final
array without making the loading process too cumbersome, such as
iterating through every item and filling item's properties in order to
keep the previously declared methods?
As far as i know there is no easy way to do this with your object implemantation. Your objects are not simple. They contains both data and functions together. So you need to define custom create function for them. But if you can able to separate this like below then you dont have to customize object construction.
For example seperate the MetadataViewModel to two different object :
--> Metadata : which contains only simple data
--> MetadataViewModel : which contains Metadata observableArray and its Metadata manipulator functions
With this structure you can call ko.mapping.fromJSON(newMetaDataArray , {} , MetadataViewModelInstance.MetadataArray) without defining a custom create function at the mapping process.

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