Reputation: 101
I am using YII2, advanced template, generate models using gii.
I have created a form with two models (A and B), all validation rules define in respective model except one rule, what is the best practice for the following case.
in form
input fields for model A. two input fields and one radio button CATEGORY (YES or NO). all require
input fields for model B. three input fields are require and
four extra input fields are depend on CATEGORY radio button, If user checked on YES than extra fields are require and if checked on NO than no need for extra fields.
so how can I define a rule for client and server side validation? in which model? one solution in my mind is create a hybrid model and define all rules with dependency
Upvotes: 3
Views: 964
Reputation: 53
I had the same problem and I find this solution.
for example if your category attribute is in model A and if it was 'yes' then item attribute in model B should be required.
for this example:
model A.php:
class A extends \yii\db\ActiveRecord
{
public $category;
public function rules()
{
return [
[['category'], 'safe'],
];
}
}
B.php class B extends \yii\db\ActiveRecord
{
public $item;
public $category;
public function rules()
{
return [
[['item'], 'safe'],
[['item'], 'required', 'when' => function($model) {
return $model->category == 'yes';
}]
];
}
}
and in controller
$a = new A();
$b = new B();
if ($a->load(Yii::$app->request->post()) && $b->load(Yii::$app->request->post())) {
$b->category= Yii::$app->request->post()['First']['category'];
$isValid = $a->validate();
$isValid = $b->validate() && $isValid;
if ($isValid) {
echo 'its valid';
}
}
Upvotes: 0