Yii2:如何将新变量从视图发送到控制器? [英] Yii2: How to send new variable from view to controller?
问题描述
我有一个名为 persons 的表,其中包含 id 和 name 字段.
I have a table called persons with id and name fields.
我有一个 create.php 视图,该视图加载了名为 Persons 的模型,现在我想添加一个名为 hasCar 的复选框以显示是否一个人有车(这是布尔条件).
I have a create.php view that loads the model called Persons and now I want to add a checkbox called hasCar to show if a person has a car (so it is a boolean condition).
然后,我具有发送按钮,该按钮会将表单的 $ model 数组发送到控制器,因此我需要添加具有 $ model 数组的> hasCar 变量.
Then I have the send button that send the $model array of the form to the controller so I need to add the hasCar variable to $model array.
但是该复选框不是 persons 表的一列,因此出现了一些错误,因为它不是模型的一部分.
But the checkbox is not a column of the persons table so I got some errors because it is not part of the model.
我以这种方式添加了该复选框,但是它当然不起作用.
I added the checkbox in this way but it is not working, of course.
<?= $form->field($model, 'hasCar')->checkbox(); ?>
是否可以在 $ model 数组中发送 hasCar 变量?我的意思是,当按下发送按钮时,如何将 hasCar 变量发送到控制器?
Is it possible to send the hasCar variable inside the $model array? I mean, how can I send the hasCar variable to the controller when the send button is pressed?
推荐答案
您不能将变量传递给与数据库表关联的$ model对象轨道,这是正确的.您需要通过请求方法(GET,POST)将变量传递给控制器.
You can't pass the variable to the $model object orbit is affiliated with a db table, you are right about this. You need to pass the variable to the controller via a request method (GET, POST).
尝试:
Yii::$app->request->post()
用于POST和:
Yii::$app->request->get()
对于GET.
还要在表单上将复选框添加为HTML类组件.
Also on the form add the checkbox as an HTML class component.
示例:
控制器:
...
$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的更多信息: 在此处输入链接描述
More on ActiveFormJS: enter link description here
我希望这个答案能对您有所帮助.
I hope this answer covered you.
达米安
这篇关于Yii2:如何将新变量从视图发送到控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!