如何将必填字段验证添加到 YII2(高级模板)中的可存储字段


How to add required field validation to custmizable field in YII2 (Advanced Template)?

>我有一个针对特定model的插入表单,并且required fields validations在该model中通过rules function运行良好。我想从另一个表在表单中添加另一个字段并提供所需的验证。怎么做?

考虑以下示例

Contact.php//型号1

...
class Contact extends Model
{
    public function rules()
    {
        return [
            ['contact_name', 'string', 'required'],
            // other attributes
        ];
    }
    ...

Users.php//模型2

...
class Users extends Model
{
    public function rules()
    {
        return [
            ['user_name', 'string', 'required'],
            // other attributes
        ];
    }
    ...

ContactController.php

...
use 'app'models'Users;
...
class ContactController extends Controller
{
    public function actionCreate()
    {
        $contact_model = new Contact;
        $users_model = new Users;
        if($contact_model->load(Yii::$app->request->post()) && $users_model->load(Yii::$app->request->post()))
        {
            // saving code
        }
        else
        {
            return $this->render('create', ['contact_model'=>$contact_model, 'users_model'=>$users_model]);
        }
    }
    ...

views/contact/_form.php

...
<?php $form = ActiveForm::begin(); ?>
        <?= $form->field($contact_model, 'contact_name')->textInput(['maxlength' => 255]) ?>
        <?= $form->field($user_model, 'user_name')->textarea(['rows' => 6]) ?>
        <!-- other inputs here -->
        <?= Html::submitButton($contact_model->isNewRecord ? Yii::t('app', 'Create') 
            : Yii::t('app', 'Update'), ['class' => $contact_model->isNewRecord 
            ? 'btn btn-success' : 'btn btn-primary']) ?>
        <?= Html::a(Yii::t('app', 'Cancel'), ['article/index'], ['class' => 'btn btn-default']) ?>
<?php ActiveForm::end(); ?>
...

在这里,来自两个不同模型的输入也会得到验证,并确保两个输入采用相同的一种形式。

使用 enableClientValidation 验证这些字段

$form = ActiveForm::begin([
    'id' => 'register-form',
    'enableClientValidation' => true,
    'options' => [
        'validateOnSubmit' => true,
        'class' => 'form'
    ],
])