Yii2创建一个没有模型的表单 [英] Yii2 create a form without a model

查看:163
本文介绍了Yii2创建一个没有模型的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在Yii2框架中没有模型的情况下创建表单,因为我正在创建mailchimp注册表单,因此模型不是必需的,下面的代码生成了表单,但是您可以看到它使用了模型.

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(); ?>

我仍然使用activeform吗,如何在不引发错误的情况下删除$ model变量?

Do I still use activeform, how can I remove the $model variable without it throwing up an error?

推荐答案

Yii2有一个很好的小东西,称为

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.

文档中的示例:

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
   }
}

显然,这些实例也可以用于ActiveForm -widget. 然后,您可以先在操作中运行适当的验证,然后将数据传递给MailChimp.如果要作为一部分运行 HTML Purifier ,可能会方便内容验证的内容

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

这篇关于Yii2创建一个没有模型的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆