douqun1977 2015-10-26 03:28
浏览 300

Yii 2.0 - 如何获取当前记录的id值然后将其保存到特定字段?

I want to create record where the particular field to be save contains the value of current model's id plus the format I made.

To get the id value I've tried to make Controller like this:

public function actionCreate()
    {
        $model = new NomorSurat();

        if ($model->load(Yii::$app->request->post()))
        {
            // Save nosurat field with particular format name
            $model->save(); // I save to get the current ID here, but return value still nothing
            $number = $model->id;
            $bulan = date('m');
            $tahun = date('Y');
            // Save with current id + custom format
            $model->nosurat = $number.'/'.'BTPN-TMH'.'/'.Yii::$app->joenmarz->romanic_number($bulan).'/'.$tahun;

            ... // some stuff

            // Then save it all, once again
            $model->save();

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

But the variable $number saved in nosurat field returns only the custom format I've made, when I tried it in my View:

...
<?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        'nosurat',
        ... // some attributes
    ],
]) ?>

Here's screenshot of the result: Result Screenshot

  • 写回答

1条回答 默认 最新

  • dongxie9448 2015-10-26 08:10
    关注

    Just add a method to your model which returns the current id and what you have saved in your database on the attribute nosurat like below and use this function for display.

    public function getNosuratDisplay()
    {
        return $this->id.$this->nosurat;
    }
    

    This of course would make it more difficult if you want to query for that attribute because the id isn't saved in the database.

    So i guess the best solution would be to generate and save this attribute in afterSave (e.g. only generate the id in insert mode i guess this is what you want).

    public function generateNosurat()
    {
       $number = $this->id;
       $bulan = date('m');
       $tahun = date('Y');
       $this->nosurat = $number.'/'.'BTPN-TMH'.'/'.Yii::$app->joenmarz->romanic_number($bulan).'/'.$tahun;
    }
    
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            $this->generateNosurat();
            $this->save();
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?