While developing the web application you are often faced a situation where you need to reuse the form validations.
There can be 2 scenarios:
First, same form used in 2 different pages. For example consider
- Form to set notification setting in Registration page
- Form to update notification setting in Settings page
And second scenario where same form used in combination with other forms.
This can be done in 2 approaches:
- Using FormRequest
- Using traits (This is much cleaner so I recommend this. You can skip to bottom to see implementation)
Case 1: Creating new form request for Mail Setting Registration page
Solution: We simply can code as below.
Case 2: A different page with same validation. Like registration and setting page. In such case Reuse Case 1’s form request as is.
Case 3: Another page needs same but only subset of it to be validated, like only 2 params ignoring others.
We can simply extend and override the protected property with needed params like below:
Note here we are specifying the paramList explicitly so even if new parent rules are added it won’t affect this request.
Case 4: A new webpage combines 2 smaller forms and shows 1 extra params.
Here we can’t extend since its a combination, instead we can create a form request that uses existing request classes to get rules and message like this:
Case 5: Similar to above, a page needs to show 2 existing forms but wants to validate only some of each forms parameters.
Lets say 2 existing forms are MailSettingFromRequest and AnotherSmallFormRequest.
Till now we are extending and overriding the protected property for selecting subset of rules and messages. Now, let’s define a new method to do same. This method by setting params will allow to cherry pick rules/messages just like overriding the class property.
We made the setParamList to return itself so that we can chain the methods.
Now we can define new request like below to combine as well as cherrypick rules/messages
In short, we should always specify which subset of param-rules pair we need for our form.
Problem of Inconsistency: Here sometimes we use property: $paramList and sometimes method: setParams() to cherry pick.
To make it consistent, above can also be done by using another method: getRules() and call it always with needed param list. The list always stays in the formRequest so its basically same.
For each form that can be reused, we simply create a trait. Trait has all the rules and based on params passed to its method it filters and return.
Only difference as compared to above approach is, instead of common forms sitting in one of Form Request, here it becomes traits.