getRequest()->getParam('image_id'); $redirect = $this->resultRedirectFactory->create(); $uploadedPaths = []; try { $image = $this->imageFactory->create(); if ($id > 0) { $image->load($id); if (!$image->getId()) { throw new LocalizedException(__('The image no longer exists.')); } } $title = trim((string) $this->getRequest()->getParam('title')); $categoryId = (int) $this->getRequest()->getParam('category_id'); if ($title === '' || !$this->categoryFactory->create()->load($categoryId)->getId()) { throw new LocalizedException(__('Title and a valid category are required.')); } $oldPaths = []; foreach (['thumbnail', 'image', 'icon'] as $field) { $pathField = $field . '_path'; $oldPaths[$field] = (string) $image->getData($pathField); $newPath = $this->mediaUploader->save($field); if ($newPath !== null) { $uploadedPaths[$field] = $newPath; $image->setData($pathField, $newPath); } elseif ($this->getRequest()->getParam('delete_' . $field)) { $image->setData($pathField, ''); } } $image->addData([ 'category_id' => $categoryId, 'title' => $title, 'description' => trim((string) $this->getRequest()->getParam('description')), 'link_url' => trim((string) $this->getRequest()->getParam('link_url')), 'status' => $this->getRequest()->getParam('status') === '0' ? 0 : 1, 'sort_order' => (int) $this->getRequest()->getParam('sort_order'), ])->save(); foreach ($oldPaths as $field => $oldPath) { $currentPath = (string) $image->getData($field . '_path'); if ($oldPath !== '' && $oldPath !== $currentPath) { $this->mediaUploader->delete($oldPath); } } $this->messageManager->addSuccessMessage(__('The image has been saved.')); return $redirect->setPath('esun_image_manager/image/index'); } catch (\Throwable $e) { foreach ($uploadedPaths as $path) { $this->mediaUploader->delete($path); } $this->messageManager->addErrorMessage($e->getMessage()); return $redirect->setPath( $id ? 'esun_image_manager/image/edit' : 'esun_image_manager/image/new', $id ? ['id' => $id] : [] ); } } }