douyan1944 2017-09-10 17:47
浏览 229
已采纳

Yii2:如何从视图向控制器发送新变量?

I have a table called persons with id and name fields.

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).

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.

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

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?

  • 写回答

2条回答 默认 最新

  • dpy3846 2017-09-10 18:13
    关注

    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).

    Try :

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

    for POST, and :

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

    for GET.

    Also on the form add the checkbox as an HTML class component.

    EXAMPLE:

    CONTROLLER:

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

    VIEW:

    ...
    // 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']) ?>
    ...
    

    More on ActiveFormJS: enter link description here

    I hope this answer covered you.

    Damian

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU