drdawt9210 2017-03-13 04:50
浏览 80

如何从不同的控制器Yii2获取ID?

**Here is the block diagram for question**

In the ActiveForm I have model button with Pjax render field after form from the modal button will created. Added a picture for an example. How can I get newly created id (not select added to the database, need to get the id that comes from this form).

I think I need to set get to button, than with ajax catch this and transfer to my Pjax rendered cell

I tried variations, but unsuccessfully, I cann't fully understand how to implement it. Can anyone help with the solution ?

//TwoController
public function actionCreate()
{
    $model = new Formtwo();

    if ($model->load(Yii::$app->request->post())) {
        if ($model->save()) {
            echo 1;
        //maybe here I must to do query ?
        } else {
            echo 0;
        }
    } else {
        return $this->renderAjax('create', [
            'model' => $model,
        ]);
    }
}

Index GridView **Index GridView**

  • 写回答

2条回答 默认 最新

  • 普通网友 2017-03-13 15:28
    关注
        //TwoController
    public function actionCreate()
    {
        $model = new Formtwo();
    
        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                echo $model->id;
            //maybe here I must to do query ?
            } else {
                echo 0;
            }
        } else {
            return $this->renderAjax('create', [
                'model' => $model,
            ]);
        }
    }
    

    You don't need query. Just use $model->id. It has value after save().

    Update

    It doesn't matter in which controller you are. You get the id of the model saved after save(). Then you can use id attribute. So, you can open modal form with ajax load. On form2 you register script to ajax post form. Something like this:

    $("#form :submit").click(function (e) {
                e.preventDefault();
                $.ajax({
                    method: "POST",
                    url: $("#form").attr("action"),
                    data: $("#form").serialize(), 
                    success: function (response) {
                        $("#modalid").modal("hide")
                        $.pjax.reload({
                            container: "#grid"
                        });
                       $('#Form2_id').val(response); //here you get the id
                    },
                })
                return false;
          });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能