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

时间:2015-02-11 13:13:56

标签: php validation yii2

我遇到的几乎是这样的:

  1. 我有create form,表单包含两个模型的属性;
  2. 我将它们从控制器传递到视图,并在两个模型中添加规则以验证属性;
  3. 但表单验证效果不佳 - 模型的验证是 不行。
  4. 我不知道如何解决这个问题,谢谢你的帮助!

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


    这是我的示例代码。

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

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

2 个答案:

答案 0 :(得分:1)

这可以是一个选项。您可以通过创建自定义模型来尝试它,例如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 ',
        ];
    }

答案 1 :(得分:1)

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,
    ]);
}