How to display validation messages with multiple models in one form27 Dec 2011 Add Comments Intermediate Level
Table Of Content
Let us assume we are building a user registration form and for each user, we will have one profile. So the relationship between User model and Profile model is one to one.
For demo purpose, we create two simple database tables (users and profiles).You will need to create these two tables in your database if you wish to run this demo.
New what we need to do is to create a form to save the profile.
This form will be submitted to ProfilesControllers's add function. Note how we name the field "name" for User model.
When working with one model, we will call model's save() function to save data. When working with associated multiple models. We will use saveAll(). But before calling saveAll(), we will need to unset the foreign key (user_id in our case) to prevent unexpected validation failure:
That is all. Now when you try to create profile with empty data, the form should automatically show your error messages for both User and Profile's fields.
Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.