Yii2:在视图中使用多个模型时如何启用表单验证?

Yii2: how to enable form validation when using multiple models in a view?

我遇到的差不多是这样的:

  1. 我有一个create form,表单包含两个模型的属性;
  2. 我将它们从控制器传递到视图,并添加规则以验证两个模型中的属性;
  3. 但表单验证效果不佳 - 模型验证是 不工作。

我不知道如何解决这个问题,谢谢帮助!

我找到了一篇参考文章 - Complex Forms with Multiple Models,但它是待定的。


这是我的示例代码。

控制器 - 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
        ]);
    }
}

型号 - 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'],
        ];
    }
}

查看 - 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(); ?>

这可以是一个选项。您可以通过创建自定义模型来尝试它,例如 ContactForm 类似这样的东西:

<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * CustomModel is the model behind the contact form.
 */
class CustomModel extends Model
{
    public $attributeFromModel1;
    public $attributeFromModel2;


    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // attributeFromModel1, attributeFromModel2 are required
            [['attributeFromModel1', 'attributeFromModel2'], 'required'],

           //  ['email', 'email'],
               ['attributeFromModel1','YourRule']
            // verifyCode needs to be entered correctly
            ['verifyCode', 'captcha'],
        ];
    }

    /**
     * @return array customized attribute labels
     */
    public function attributeLabels()
    {
        return [
            'atttributeFromModel1' => 'Your Label',
             'atttributeFromModel2' => 'Your Label ',
        ];
    }
public function actionUpdate($id)
{
    $model = $this->findModel($id);
    $customerModel = Customer::findOne($id);

    if (!isset($model, $customerModel)) {
        throw new NotFoundHttpException("The user was not found.");
    }

    $model->scenario = 'update';
    $customerModel->scenario = 'update';

    if ($model->load(Yii::$app->request->post()) && $customerModel->load(Yii::$app->request->post())) {
        $isValid = $model->validate();
        $isValid = $customerModel->validate() && $isValid;
        if ($isValid) {
            $model->save(false);
            $customerModel->save(false);
            return $this->redirect(['view', 'id' => $id]);
        }
    }

    return $this->render('update', [
        'model' => $model,
        'customerModel' => $customerModel,
    ]);
}