Initializing JPA subentities when submitting JSF datatable - jpa

I've recently received a business requirement for my JSF app to edit rows of a datatable, in the table itself.
The problem: the table is backed by a list of JPA entities, but the editable fields belong to their -optional- associations. So, as an example of such an editable selectOneListbox field, if I do:
<h:selectOneListbox id="rca" value="#{mainEntity.associatedEntity.rca}" converter="omnifaces.SelectItemsConverter">
<f:selectItem itemValue="#{null}" itemLabel="" />
<f:selectItems value="#{rcaOptions}" var="rca" itemLabel="#{rca}" itemValue="#{rca}" />
</h:selectOneListbox>
I eventually receive Target Unreachable, 'associatedEntity' returned null when submitting the table, for those rows where there is no associated entity yet, even if I left the selectOneListbox unchanged for those (null option selected). The questions:
how/where/when can I elegantly instantiate new subentities when submitting the form, only for those rows the user acted on (ajax-less preferably), preventing the error shown above? Forcibly creating subentities in the model for all rows when first rendering the table is IMHO a flaw in design.
How can I programmatically ignore this selectOneListbox -or any other input field- from the entire JSF lifecycle, conditionally, just like if the field never existed in the request? I tried implementing several converters and validators but the validation phase is still trying to get the value reference, no matter what I try, throwing the error shown above

Related

How to determine the fields that changed whilst editing an entity

I have a logger added that store logs when an entity is saved. What I am trying to get is how would I determine which fields have been edited for instance if I have 5 columns in one entity and I change only two columns so I would like to get the difference of only those two columns as they have been edited.
Something like $entity->change() so it would provide me old and new values of those two columns. I am trying to find out in zend but sadly haven't progressed any further.

Symfony2: Collection of dropdown select lists for a many-to-many relationship

The objective:
Having a many-to-many relation be displayed as a dynamic list of select inputs(single choice dropdown list)
User arrives on page with a single select field (multiple = false) populated with persisted entities and add/remove buttons. By clicking the add button, a new select field with the same options appears below the first, which adds a new entry in the M2M relation. By clicking remove the field disappears and the entry should be removed.
The model:
Two entities: User & Manager. A User has exactly one "special" Manager and unlimited normal Managers.
Managers manage unlimited users.To model this I have created two relationships for which the user is the "owner" (not sure how to translate this)
ManyToOne specialManager
ManyToMany normalManagers
I haven't created a many to many relationship with attribute "special" because the requirement is exactly one special manager and I wasn't sure if Symfony/Doctrine would cause problems down the line.
What I have:
I can display a multiple select field with the existing entities using Entity field type, as per the documentation. Functionally this is what I need, visually it is not.
I can also use the Collection field type to display a single text field, and add or remove more with JS, as per the documentation. Visually this is what I need, but The text fields (entity attribute) need to be replaced by choice field.
The question:
Before I continue digging, is there a simple way to achieve this list of select tags?
For anyone else who may eventually need a dynamic list of select fields:
I initially solved this issue by detaching the field(s) in event listeners, and handling the display/submission manually in the controller.
However I wasn't satisfied with this clunky solution and when I encountered the same need I used a second solution: creating an intermediary entity xxxChoice (in this case ManagerChoice) which is Mto1 inversed related to User and Mto1 related to Manager. Then by creating a ManagerChoiceType form with "Manager" entity field type I was able to easily display my collection of dropdown select lists.

Foreign entity in form into different kind of input

I have two entities: product and category (Symfony 2.3).
I want to create a form in which an user can choose a product by first selecting the category. A user selects the category by clicking on image, then I want to set the image's value into a hidden input, but I don't see how can I change a foreign entity choice list to a hidden input (http://symfony.com/doc/current/reference/forms/types/entity.html).
How can I accomplish this? (how to change form input to hidden)
If I set cascade validation to true, will it for example check if a category really exist. (To prevent putting products with non-existing category from malicious users) ?
Part 1
To do this you need to use a data transformer to do two things:
transform an entity into an identifier that is either a string or integer so a form can render it as a hidden field.
transform the string or integer identifier into the entity when the form is submitted so that the parent entity can be saved with the correct relationship
The symfony docs I linked to above (here too) actually walk though an entire example of using a data transformer with a form.
As a shameless plug (because I believe it is helpful) I have written a little tutorial on using a data transformer for a hidden field with an entity id: http://lrotherfield.com/blog/symfony2-forms-entity-as-hidden-field/
Part 2
If you are using the data transformer then you don't need to worry about malicious users. The data transformer will fail because it will not be able to reverse transform the category from the fake id. In my tutorial the transformer will throw a Symfony\Component\Form\Exception\TransformationFailedException exception.
You can also write a validator (potentially using a call back) if you wanted that checks that the submitted category is real if you want an error to show in the form. Doctrine wont allow you to persist a fake category relationship as the foreign key constraint will fail.

web2py Validation

I would like to know validation is a must, on fields which are not present on the form but are available in the table. Does marking them as NULL in the define_table make them validated only when they are present in the form?
The form validators apply only to forms, so will not affect fields that are not present in the form. I'm not sure what you mean by marking a field as NULL, but if you are referring to Field(..., notnull=True), that executes the SQL NOT NULL statement when the database table is first created (assuming DAL migrations are enabled). That option is enforced by the database itself whenever a record is inserted or updated (via a form or any other method). If a notnull field is left empty, it will result in an operational error from the database.

Entity Framework 5 SaveChanges Not Working, No Error

None of the many questions on this topic seem to match my situation. I have a large data model. In certain cases, only a few of the fields need be displayed on the UI, so for those I replaced the LINQ to Entity query that pulls in everything with an Entity SQL query retrieving only the columns needed, using a Type constructor so that I got an entity returned and not a DbDataRecord, like this:
SELECT VALUE MyModelNameSpace.INCIDENT(incident.FieldA, incident.FieldB, ...) FROM ... AS ...
This works and displays the fields in the UI. And if I make a change, the change makes it back to the entity model when I tab out of the UI element. But when I do a SaveChanges, the changes do not get persisted to the database. No errors show up in the Log. Now if I very carefully replace the above query with an Entity Sql query that retrieves the entire entity, like this:
SELECT VALUE incident FROM MyDB.INCIDENTs AS incident...
Changes do get persisted in the database! So as a test, I created another query like the first that named every column in the entity, which should be the exact equivalent of the second Entity SQL query. Yet it did not persist changes to the database either.
I've tried setting the MergeOption on the returned result to PreserveChanges, to start tracking, like this:
incidents.MergeOption = MergeOption.PreserveChanges;
But that has no effect. But really, if retrieving the entire entity with Entity Sql persists changes, what logical purpose would there be for behaving differently when a subset of the fields are retrieved? I'm wondering if this is a bug?
Gert was correct, the problem was that the entity was not attached. Dank U wel, Gert! Ik was ervan verbluft!
I just wanted to add a little detail to show the full solution. Basically, the ObjectContext has an Attach method, so you'd think that would be it. However, when your Entity SQL select statement names columns, and you create the object using a Type as I did, the EntityKey is not created, and ObjectContext.Attach fails. After trying and failing to insert the EntityKey I created myself, I stumbled across ObjectSet.Attach, added in Entity Framework 4. Instead of failing, it creates the EntityKey if it is missing. Nice touch.
The code was (this can probably be done in fewer steps, but I know this works):
var QueryString = "SELECT VALUE RunTimeUIDesigner.INCIDENT (incident.INCIDENT_NBR,incident.LOCATION,etc"
ObjectQuery<INCIDENT> incidents = orbcadDB.CreateQuery<INCIDENT>(QueryString);
incidents.MergeOption = MergeOption.PreserveChanges;
List<INCIDENT> retrievedIncidents = incidents.ToList<INCIDENT>();
orbcadDB.INCIDENTs.Attach(retrievedIncidents[0]);
iNCIDENTsViewSource.Source = retrievedIncidents;