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