如何在YII2(高级模板)中向可定制字段添加必需的字段验证?

时间:2016-02-08 19:22:19

标签: php yii2

我有一个特定model的插入表单,而required fields validationsrules function中通过model很有效。我想在另一个表的表单中添加另一个字段并给出所需的验证。怎么做?

2 个答案:

答案 0 :(得分:4)

考虑以下示例

Contact.php // model1

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

Users.php // model2

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

此处来自两个不同模型的输入也得到验证,并确保两个输入都是同一种形式。

答案 1 :(得分:2)

使用enableClientValidation验证这些字段

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