【问题标题】:Yii2: How to send new variable from view to controller?Yii2:如何将新变量从视图发送到控制器?
【发布时间】:2017-09-10 17:47:55
【问题描述】:

我有一个名为 persons 的表,其中包含 idname 字段。

我有一个 create.php 视图来加载名为 Persons 的模型,现在我想添加一个名为 hasCar 的复选框来显示是否一个人有车(所以这是一个布尔条件)。

然后我有 send 按钮将 form$model 数组发送到控制器,所以我需要添加 hasCar 变量到 $model 数组。

但复选框不是 persons 表的列,所以我收到了一些错误,因为它不是模型的一部分。

我以这种方式添加了复选框,但它当然不起作用。

<?= $form->field($model, 'hasCar')->checkbox(); ?>

是否可以在 $model 数组中发送 hasCar 变量?我的意思是,当按下 send 按钮时,如何将 hasCar 变量发送到控制器?

【问题讨论】:

标签: php model-view-controller yii2 yii2-advanced-app


【解决方案1】:

创建一个新的模型扩展 Person 包含 hasCar 成员,并从 PersonForm 类加载模型,例如:

class PersonForm extends Person
{
    public $hasCar;

    public function rules()
    {
        return array_merge(parent::rules(), [
            [['hasCar'], 'safe'],
        ]);
    }   

    public function attributeLabels()
    {
        return array_merge(parent::attributeLabels(), [
            'hasCar' => 'Has car',
        ]);
    }      
}

【讨论】:

    【解决方案2】:

    你不能将变量传递给 $model 对象轨道附属于一个 db 表,你是对的。您需要通过请求方法(GET、POST)将变量传递给控制器​​。

    试试:

    Yii::$app->request->post()
    

    对于 POST,以及:

    Yii::$app->request->get()
    

    对于 GET。

    同样在表单上添加复选框作为 HTML 类组件。

    示例:

    控制器:

    ...
    $hasCar = Yii::$app->request->post('hasCar');
    ....
    

    查看:

    ...
    // We use ActiveFormJS here
    $this->registerJs(
        $('#my-form').on('beforeSubmit', function (e) {
            if (typeof $('#hasCar-checkbox').prop('value') !== 'undefined') {
                return false; // false to cancel submit
            }
        return true; // true to continue submit
    });
    $this::POS_READY,
    'form-before-submit-handler'
    );
    ...
    <?= HTML::checkbox('hasCar', false, ['id' => 'hasCar-checkbox', 'class' => 'form-control']) ?>
    ...
    

    更多关于 ActiveFormJS: enter link description here

    我希望这个答案涵盖了你。

    达米安

    【讨论】:

    • hasCar 变量应该是必需的。我该如何验证它?我可以在模型文件中做到这一点,但我不想使用模型。
    • 您不能使用后端验证。 Yii2 有一个关于此问题的已知错误,但尚未解决。您可以使用前端验证。至少我是这样做的。您首先将处理程序附加到 activeform 提交事件。我会用一个例子来更新我的答案。
    猜你喜欢
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多