I have this create action in Yii2 controller:
public function actionCreate2()
{
$searchModel = new BibliografieSearch();
$searchModel = new CodiciSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$model = new Elenchi();
$model->Modified = date( 'y-m-d' );
if ($model->FogliDaO) {
$model->FogliDaO = str_pad($model->FogliDaO, 8, "0", STR_PAD_LEFT);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index', 'sort' => '-IDElenco']);
}
return $this->render('create2', [
'model' => $model,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel
]);
}
Now, if I write "28v" in field (FogliDaO) and I save the new record the result in Mysql database is always "28v", instead of "0000028v". Where I'm wrong? (FogliDaO is VARCHAR). I need help. Thank you very much!!!!
If you want change the content of the $model you mustassign the padded value after the load() and before the save() function .. otherwise you overwrite the assigment
public function actionCreate2()
{
$searchModel = new BibliografieSearch();
$searchModel = new CodiciSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$model = new Elenchi();
if ($model->load(Yii::$app->request->post()) ) {
$model->Modified = date( 'y-m-d' );
if ($model->FogliDaO) {
$model->FogliDaO = str_pad($model->FogliDaO, 8, "0", STR_PAD_LEFT);
}
$model->save();
return $this->redirect(['index', 'sort' => '-IDElenco']);
}
return $this->render('create2', [
'model' => $model,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel
]);
}
the $model->load() function copy the correspondent model data from $_POST to your actual (new) model .. so if you assign the padded value before the load() function this value is lost because the load overwrite this value with the $_POST content