Create Form With DynamicModel

You are viewing revision #1 of this wiki article.
This is the latest version of this article.

In yii2 we can create form without create FormModel. Here we go

// in controller

public function actionForm()
    $model = new \yii\base\DynamicModel([
        'name', 'email', 'address'
    $model->addRule(['name','email'], 'required')
        ->addRule(['email'], 'email')
        ->addRule('address', 'string',['max'=>32]);

        // do somenthing with model
        return $this->redirect(['view']);
    return $this->render('form', ['model'=>$model]);

and then in form.php

<div class="form">

    <?php $form = ActiveForm::begin(); ?>

        <?= $form->field($model, 'name') ?>
        <?= $form->field($model, 'email') ?>
        <?= $form->field($model, 'address') ?>
        <div class="form-group">
            <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
    <?php ActiveForm::end(); ?>

</div><!-- form -->