What I meet is almost like this:
- I have a
create form, and the form contains two model's attribute; - I pass them from controller to view, and add rules to validate attribute in both model;
- But the form validation did not work well - a model's validation is not work.
I have no idea about how to resolve this, thanks for help!
And I find a reference article - Complex Forms with Multiple Models, but it is TBD.
Here is my sample code.
Controller - SiteController.php:
namespace task\controllers;
use yii\web\Controller;
use task\models\Task;
use task\models\Customer;
class Task extends Controller
{
public function actionCreate()
{
$model = new Task;
$customerModel = new Customer;
// load, validate, save ...
return $this->render('create', [
'model' => $model,
'customerModel' => $customerModel
]);
}
}
Model - Task.php, Customer.php:
namespace task\models;
use yii\db\ActiveRecord;
class Task extends AcitveRecord
{
public $title, $published_at;
public function rules()
{
return [
[['title', 'published_at'], 'required'],
['published_at', 'match', 'pattern' => '/patten for time/']
];
}
}
namespace task\models;
use yii\db\ActiveRecord;
class Customer extends ActiveRecord
{
public $name;
public function rules()
{
return [
['name', 'required'],
];
}
}
View - create.php:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'title')->textInput() ?>
<?= $form->field($model, 'publish_at')->textInput() ?>
<?= $form->field($customerModel, 'name')->textInput() ?>
<?= Html::submitButton('submit')?>
<?php ActiveForm::end(); ?>