Yii 2.0: Create Form With DynamicModel

7 followers

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]);
 
    if($model->load(Yii::$app->request->post())){
        // 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']) ?>
        </div>
    <?php ActiveForm::end(); ?>
 
</div><!-- form -->

Total 4 comments

#18765 report it
Misbahul D Munir at 2015/01/01 05:03am
@VivekYii

yii2-upload-file

add config in common

'controllerMap' => [
        'file' => 'mdm\\upload\\FileController', // use to show or download file
    ],

Then you can access with ?r=file&id=$id

#18764 report it
VivekYii at 2015/01/01 04:33am
How can we use in yii2 advance backend for frontend acccess

Hi

how can we upload single file to folder and information to database of backend for access in frontend users.....

#18344 report it
Misbahul D Munir at 2014/10/19 05:06am
@VivekYii

What do you mean? look this posting

#18343 report it
VivekYii at 2014/10/19 03:46am
wow how can upload photo in above example

Thanks for tutorial Its gr8 . but how to upload image in this

Leave a comment

Please to leave your comment.

Write new article
  • Written by: Misbahul D Munir
  • Category: Tips
  • Yii Version: 2.0
  • Votes: +2 / -1
  • Viewed: 19,406 times
  • Created on: Oct 18, 2014
  • Last updated: never
  • Tags: form, yii2, model