Reputation: 2509
This is a question about best practices. In general, when is it better to use Form Validation (i.e: Create a form for the request being sent). And when is it better to rely on the ActiveRecord validation.
Example: I have a model Customer and model Address where each customer has more than one address. In the form to create Customer, I want to send more than one address
{
"name": "customer",
"vat_no": "12345678",
"time_zone": 277,
"category": 1,
"email": "[email protected]",
"addresses":[
{
"street_address": "abcd...",
"phone": 1234567
},
{
"street_address": "hdhdh...",
"phone": 2345678
}
]}
**This is a question inspired by a previous question that I asked here Yii2 - Validating nested objects, and specifically about the answer given there
Upvotes: 0
Views: 160
Reputation: 9402
It partly depends how closely your form aligns to your models - e.g., how much will you need to transform the form data, are the validation rules the same and how many models are required.
In your case, if there are only 2 models and the logic is pretty clear that the primary model is Customer and secondary is Address, it's really personal preference. You could use a scenario for the form and have scenario-specific rules in the existing models or in a dedicated Form model. If, for whatever reason, the form fields have different validation requirements than the database, it might be cleaner to have them in a separate model.
Ultimately the code has to go somewhere, so you want to think about what's going to make the most sense for you to maintain -- e.g., you want to keep data functions out of the controller, so do you want to use the CustomerController or create one for this purpose? If you use a Form model, you might then want a matching controller and keep the primary models focused on table-specific CRUD operations.
Upvotes: 3
Reputation: 1338
It is always a best practice to keep the size of your code base to a minimum.
Thus, if using multiple models works for you, don't create (unnecessary) extra code by adding a form model.
Upvotes: 0