8

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?

con322
  • 1,119
  • 7
  • 16
  • 29
  • 1
    Don't know YII, but You can always use plain ol' html.... – Damien Pirsy Feb 04 '15 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 Feb 04 '15 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 Jul 01 '15 at 12:29

3 Answers3

11

Yii2 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

Blizz
  • 8,082
  • 2
  • 33
  • 53
5

use Html Input with active form <?=Html::input('text','','',['class'=>'form-control'])?>

  • Please complete your answer. Are you suggesting using the html helper to build the mailchimp subscription form? – MEM Aug 27 '15 at 05:59
  • @MEM he has provided the correct answer IMHO. What else would he provide? That's the exact widget you need. – Gogol Jun 10 '16 at 12:54
0

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.

ZeiZ
  • 404
  • 1
  • 5
  • 14
  • Thanks for the advice/info. So are you advising me to use a model even when sending the post data straight from the app to mailchimp list? – con322 Feb 05 '15 at 18:22