I have a database where it is somewhat common for 3 of the same tables to be linked in an exclusive manner. Imagine something like this: payments table has (customer_id, partner_id, agency_id), but only one of them is ever selected.
This is kinda cumbersome in forms, and I have been solving it on the frontend but I am thinking maybe this could be handled better with a behavior. So when you save a payment, you post a field called sender_id and it has a value like customer_id-20, which is the record with id 20 in the customers table.
Any table with this behavior could take sender_id in beforeMarshal and convert it to customer_id of 20 or whatever.
What I am unsure of is I would also like to expose a sender_id field on the output side, that parses the customer_id, partner_id and agency_id fields and converts them to the equivalent sender_id value. I know this would be easy with a virtual field, but is it possible to create a virtual field as part of a behavior (or a trait I guess) and also add it to the $_virtual property of the entity (without overwriting any that are set in the entity)?
I am trying to picture a scenario where it’s easier to send “sender_id = customer_id-20” than it is to send “customer_id = 20”. Definitely seems to me like something best solved in the front end, e.g. with fields that are only shown in certain scenarios.
I guess if the intent is to have a single drop-down with sections for customer, partner or agency, this might make sense. If so, I’d likely handle it with beforeMarshal, not a behavior.
Yeah this is it exactly, a payment only has one “sender” and I want it to just be a list of these three tables from a single dropdown. I have about 4 tables that all do this, which is why I was thinking a behavior might make sense.
Currently my frontend just gets a list from each table, combines them into a single select and then converts it to the three fields before sending the request to the backend.
Then sure, a behavior that implements beforeMarshal would seem like the way to go.
But a behavior applies to models not entities, so it’s not possible to use that to create a virtual field. You could use a trait to add that virtual accessor function to the relevant entities, but I think you’d need to manually add it to the $_virtual property.