One Form with Related Data Fields

I have three tables; products, directions and warnings. Directions and warnings are related to products by foreign keys in products. The directionsID and warningsID fields are required in products.

I am trying to use one form to create a new product with the warnings and directions. I need to insert the directions and warnings before the products are saved and retrieve the ids for directions and warnings and assign the values to directionID and warningID fields to meet the products model’s validation requirement.

I have looked at beforeSave() and loadMultiple() without success. What is the best way to approach this?

Since I’m guessing you don’t want to create the warnings and directions before the actual product is created (or passed validation since the validation can fail…) you would need to create them after the validation has passed, right?

So remove the warningID etc. from your required rules. Then add a ON_BEFORE_SAVE or ON_AFTER_VALIDATION event to your init() function and check for $this->isNewRecord. If true create your warning and direction, get the ID’s, add them to $this->warningID and run save() depedning on if you are doing it before save or after validation.

Does that sounds like a good solution?

Nice approach. It does leave an update vulnerable to an accidental removal of the directionsID and warningsID. I suppose this can be handled if $this->isNewRecord fails.

Sounds like today’s project.

Yeah you need to add some logic as well to make sure its a new record, and not a record update like you mention.

You can always check for $this->id as well if it has a value or not.

Good luck

If it’s just a true one to one relation I don’t see any reason to separate your warnings and directions from the product table. All you’re doing is making your code base larger / more complicated and running more queries.

It’s one to many. Some products share directions and/or warnings.