I want to upload an image and save it into my database.
Here, the field name in database is image_path. When, I am trying to upload my image it shows an error: Call to a member function saveAs() on a non-object on line
$customer->file->saveAs('uploads/customer/' . $customer->file->baseName . '.' . $customer->file->extension);
If I print var_dump($customer->file); it returns NULL.
Can anyone help me to resolve this issue.
This is my view:
<?php $form = ActiveForm::begin([
'id' => 'my-profile',
'action' => \Yii::$app->urlManager->createUrl(['/myprofile', 'id_customer' => Yii::$app->user->identity->id_customer]),
'options' => ['enctype'=>'multipart/form-data']
]); ?>
<?= $form->field($customer, 'file')->fileInput() ?>
<?php ActiveForm::end(); ?>
This is my Model:
public $file;
public function rules()
{
return [
['active', 'default', 'value' => self::STATUS_ACTIVE],
['active', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
[['file'],'file'],
[['name', 'image_path'], 'string', 'max' => 200],
];
}
public function attributeLabels()
{
return [
'file' => 'Profile Picture ',
];
}
This is my controller:
public function actionMyprofile(){
$customer->file = UploadedFile::getInstance($customer,'image_path');
$customer->file->saveAs('uploads/customer/' . $customer->file->baseName . '.' . $customer->file->extension);
$customer->file = 'uploads/customer/' . $customer->file->baseName . '.' . $customer->file->extension;
}
image_pathwithfilein controller, see your model rules.UploadedFile::getInstance($customer,'image_path');should beUploadedFile::getInstance($customer,'file');, since<?= $form->field($customer, 'file')->fileInput() ?>