ActiveForm without model yii2

房东的猫 提交于 2019-12-12 12:20:48

问题


I want to create ActiveForm without model for just in case something. I did try with dynamicModel but i got some error :

use yii\base\DynamicModel;
$model = DynamicModel::validateData(compact('KOMENTAR'), [
   [['KOMENTAR'], 'string', 'max' => 128],
]);

This is the form i want to create

<br>
<?php $form = ActiveForm::begin([
    'method' => 'post',
]); ?>

<?= $form->field($model, 'KOMENTAR')->textarea(['rows' => 6])->label(false) ?>

<div class="form-group">
    <?= Html::submitButton('POST', ['class' => 'btn btn-primary']) ?>
</div>

This is the error

Getting unknown property: yii\base\DynamicModel::KOMENTAR

回答1:


Since you are using compact('KOMENTAR'), you should have a $KOMENTAR variable.

Read more about compact : http://php.net/manual/fr/function.compact.php

Or you should simply create your model like this :

$model = new \yii\base\DynamicModel(['KOMENTAR']);
$model->addRule(['KOMENTAR'], 'string', ['max' => 128]);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    // do what you want 
}



回答2:


Normally ActiveItems are used to work with a model, but Yii2 have a helper class called Html to use the same items like classic HTML.

Use beginForm() method from Html. And try something like that:

use yii\helpers\Html;

<?= Html::beginForm(['/controller/view', 'id' => $model->id], 'POST'); ?>
<?= Html::textarea('KOMENTAR', '', ['rows' => 6])->label(false); ?>
<div class="form-group">
    <?= Html::submitButton('POST', ['class' => 'btn btn-primary']); ?>
</div>
<?= Html::endForm(); ?>

You can read more about this helper in the documentation.



来源:https://stackoverflow.com/questions/32368084/activeform-without-model-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!