How to display validation messages with multiple models in one form
27 Dec 2011 Add Comments Intermediate LevelTable Of Content
Content
1.Models' relationship
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.
2.Create form
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.
3.Modify save() function
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.
4.The end
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.



1 Comments
i am also used but how can edit data in this conditions.If u have any suggestion please reply me