In my case each 'Line Item', could have an undetermined number of related 'Shipper' documents associated with that line item. It was important that the Shipper documents were separate documents, and not part of a collection of the Line Item. The reason being that I needed to emulate the back end data structure of the system I was replacing.
Back to my issue, what I was attempted to do was to create a Shipper managed bean. I then bound the four input fields directly to the bean, and then called the saveShipper() method of the bean. This did work, but only for the first Shipper doc. If I tried to create another document, nothing would happen. After trying many things, I came to the conclusion that fundamentally I was doing something wrong. At this point, I decided to call on Stack Overflow, and see what advice I could receive. Here is a link to my question. (I think I could have chosen a better title but so be it.)
The advice I received was good from all three who answered, but the advice that helped the most was from Peter Presnell when he said "I would suggest not using a managed bean as it does not seem to add much value to your process. " He went on to say that the way I was attempting to reuse the managed instance causes issues. I now have firsthand knowledge that this approach causes issues. This got me to thinking that there were cases where using a managed bean was not the best way for coding.
For cases when you have more than one related objects that you want to create, and each should be saved independently, the best approach (IMO) is to make the object a POJO or Plain Old Java Object.
One thing to understand about managed beans is that there is always only one instance of each. I don't think I quite understood this before I came across this problem.
The only changes I had to do to convert the bean to a POJO was to:
- Remove the reference in the faces-config file
- Create a constructor with arguments accepting values for each instance variable
- Change the binding of the input fields from the bean to a RequestScope variable
- Change the button to create the new object in SSJS. See example below.
The code to create the java object in SSJS is:
var x - new com.yourpackage.pojoName(requestScope.field1 ...);
You can then call any method of the object by using the reference you used which was 'x' in my example.
In my case, I create a new object each time, overwriting the previous one.
I am glad this issue happened, as now my mind is more open to ways to use regular java objects in my applications.