Answer the question
In order to leave comments, you need to log in
How to upload image in actionUpdate in yii2?
Hello, I'm using the kartik FileInput plugin to upload images. Everything works fine.
The problem is that when I want to update the model, the picture is not loaded.
public function actionUpdate($id)
{
$object = Object::findOne($id);
if ($object->load(Yii::$app->request->post()))
{
$directory = Yii::getAlias('@webroot') . '/uploads/Object/';
$file = UploadedFile::getInstance($object, 'image');
if ($file)
{
$object->image = strtotime('now') . '_' . Yii::$app->getSecurity()->generateRandomString(10) . '.' . $file->extension;
if ($file->saveAs($directory . $object->image))
{
$image = Yii::$app->image->load($directory . $object->image);
$image->resize(800, null, \Yii\image\drivers\Image::PRECISE)->save($directory . $object->image, 85);
$image = Yii::$app->image->load($directory . $object->image);
$image->resize('100', '100', Yii\image\drivers\Image::INVERSE);
$image->crop('100', '100');
$image->save($directory . 'thumb/' . $object->image, 90);
}
}
if ($object->save() && $object->validate())
{
Yii::$app->session->setFlash('object-create-success');
}
else
{
Yii::$app->session->setFlash('object-action-error');
}
return $this->redirect(['/dispatcher/object']);
}
return $this->render('update', [
'model' => $object,
]);
}
<?= $form->field($model, 'image')->widget(FileInput::className(), [
'name' => 'image',
'language' => 'ru',
'options' => [
'multiple' => false,
],
'pluginOptions' => [
'uploadUrl' => Url::to(['/site/save-image']),
'theme' => "fa",
'maxFileCount' => 10,
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'dropZoneEnabled' => false,
'browseClass' => 'dfx-btn dfx-btn-out upload-image',
'uploadClass' => 'dfx-btn dfx-btn-out upload-image',
'browseLabel' => 'Изменить изображение'
]
])->label('Изображение'); ?>
Answer the question
In order to leave comments, you need to log in
In order for pictures to be visible when editing, you need to configure several widget parameters.
'pluginOptions' => [
// остальные настройки
'deleteUrl' => Url::to(['delete-img']), // укажите реальный путь к действию удаления изображений.
'initialPreviewAsData' => true,
'overwriteInitial'=>false,
'initialPreview' => !$model->isNewRecord ? $model->imagesLinks : [],
'initialPreviewConfig' => !$model->isNewRecord ? $model->imagesLinksData : [],
// остальные настройки.
]
public function getImagesLinks()
{
$path = ArrayHelper::getColumn(UploadsFiles::find()->all(), 'pathImg');
return $path;
}
public function getImagesLinksData()
{
$files = UploadsFiles::find()->all();
return ArrayHelper::toArray($files,[
UploadsFiles::class => [
'caption' => 'file',
'key' => 'id'
]
]);
}
// getPathImg() возвращает путь к изображению, используется в getImagesLinks()
public function getPathImg()
{
return Url::home(true) . 'uploads/' . $this->file;
}
$this->registerJs('
// #uploadsfiles-imagesfile - id Вашего FileInput
$("#uploadsfiles-imagesfile").on("fileuploaded", function(event, data, previewId, index) {
input.fileinput("destroy").fileinput({
multiple: true,
showUpload: false,
showRemove: false,
initialPreviewAsData: true,
overwriteInitial: false,
uploadUrl: "' . Url::to(['upload-img']) . '", // подставить реальный путь к действию
deleteUrl: "' . Url::to(['delete-img']) . '", // подставить реальный путь к действию
initialPreview: data.response.initialPreview,
initialPreviewConfig: data.response.initialPreviewData,
})
input.closest("form").find("button").attr("disabled", false)
console.log(data);
});
', View::POS_END);
public function actionUploadImg()
{
$model = new UploadsFiles();
if(Yii::$app->request->isAjax){
$model->imagesFile = UploadedFile::getInstance($model, 'imagesFile');
if($model->upload()){
$model->load(Yii::$app->request->post());
$model->saveImg();
$answer['initialPreview'] = $model->getImagesLinks();
$answer['initialPreviewData'] = $model->getImagesLinksData();
return json_encode($answer);
}
}
return false;
}
public function actionDeleteImg()
{
if(Yii::$app->request->isAjax){
$model = UploadsFiles::find()->where('id=:id', [':id' => Yii::$app->request->post('key')])->one();
FileHelper::unlink('uploads/' . $model->file);
$model->delete();
return Json::encode('Delete');
}
return false;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question