Trying to figure out a decent approach here...
I have a form, where based on if a user selects a drop down in the form or not, it shows or hides a few other form fields. If the form fields are visible I want them to be required. If they are not visible, I do not want them to be required.
I'm trying to figure out an approach for handling this inside my model rules - I tried something like this in my model rules() function:
$requiredFields = 'cashAtClosing, offerPrice, closingDate, financingType,surveyDays,'.
'earnestMoney, escrowAgent, escrowAgentAddress, surveyProvider, surveyDays, titlePolicyPayment,'.
'titleObjectionDays, titleCompany, titleCompanyAddress, optionFee, optionDays, optionCredit';
if ($this->financingType == "THIRDPARTYFINANCE")
{
Yii::trace("Add Financing Type Rules");
$requiredFields .= ',creditApprovalRequired,creditApprovalDays,loan1Amount, loan1DueInFullYears, '.
'loan1InterestNotToExceed, loan1InterestNotToExceedYears, loan1OriginationNotToExceed';
}
else
{
$safeFields .= ',creditApprovalRequired,creditApprovalDays,loan1Amount, loan1DueInFullYears, '.
'loan1InterestNotToExceed, loan1InterestNotToExceedYears, loan1OriginationNotToExceed';
}
array_push($rulesArray, array($requiredFields, 'required'));
problem is that it seems that the rules function is called prior to the model being populated so in my example here $this->financingType is always empty so this code doesn't wok.
Whats a better approach here?
Thanks.
Try to add this code to beforeValidate() method of your model. It's should help you.
But create $rulesArray property in your model. Add new rules to this variable via $this->rulesArray in beforeValidate() method and use this variable in your rules() method.