I was wondering how can I create a form without a model in Yii2 framework as I am creating a mailchimp signup form so a model isn't necessary the below code generates a form however as you can see it uses a model.
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => 255]) ?>
<?php ActiveForm::end(); ?>
Do I still use activeform, how can I remove the $model variable without it throwing up an error?
I was wondering how can I create a form without a model in Yii2 framework as I am creating a mailchimp signup form so a model isn't necessary the below code generates a form however as you can see it uses a model.
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => 255]) ?>
<?php ActiveForm::end(); ?>
Do I still use activeform, how can I remove the $model variable without it throwing up an error?
Share Improve this question asked Feb 4, 2015 at 21:09 con322con322 1,1297 gold badges16 silver badges30 bronze badges 3- 1 Don't know YII, but You can always use plain ol' html.... – Damien Pirsy Commented Feb 4, 2015 at 21:13
- @DamienPirsy yeah I was just wondering if it's possible which I am guessing it is however as you say normal html will do the job. – con322 Commented Feb 4, 2015 at 21:16
- @DamienPirsy That's the way to go, but YII2 is horrible when it comes to forms, it's nearly impossible to get a form's input into a model. Good reason NOT to use a framework! – Sliq Commented Jul 1, 2015 at 12:29
3 Answers
Reset to default 11Yii2 has this nice little thingy called a DynamicModel
.
This basically allows you to create a model on the fly so that you can still use all the ActiveForm
and validation goodies, but without having to commit to writing an entire model class for it. Might be interesting.
Example from the documentation:
public function actionSearch($name, $email)
{
$model = DynamicModel::validateData(compact('name', 'email'), [
[['name', 'email'], 'string', 'max' => 128],
['email', 'email'],
]);
if ($model->hasErrors()) {
// validation fails
} else {
// validation succeeds
}
}
Obviously these instance can also be used for the ActiveForm
-widget.
You can then run proper validation in your actions first and then pass on your data to MailChimp. Might be handy if you want to run HTML Purifier
as part of that validation for the content
use Html Input
with active form
<?=Html::input('text','','',['class'=>'form-control'])?>
As @DamienPirsy suggested - use plain. If you want use yii2 features for it - use Class yii\helpers\BaseHtml (http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html) There are all methods to build any form as you want. Then you can operate it in any action in any controller of your application. But this is not true MVC way. That's why Yii/Yii2 advises you to use models.