我写了一个自定义滑块模块,其中包含幻灯片项目表单。在此表单中,有一个图像字段用于上传图像。
当我第一次创建带有图像的幻灯片项目时,一切正常,我可以检索所有数据,但是当我编辑它并再次保存时,我收到了这个错误:
1个异常:异常#0(例外):注意:数组到字符串 转换 /Users/louisserre/Sites/messika/lib/internal/Magento/Framework/Data/Form/Element/Image.php 第51行
即使图片字段未更改,我也收到此错误。
在此文件的ligne 51处,代码为:
public function getElementHtml(){
$html = '';
if ((string)$this->getValue()) {
我记录了$ this-> getValue(),当我第一次创建幻灯片项目时,我得到了:imagepath / image.jpg,当我编辑时,我得到了数组([value] => http://imagepath/image.jpg)幻灯片项目。
这是我的表单字段代码:
$fieldset->addField('image_url', 'image', [
'label' => __('Image'),
'title' => __('Image'),
'name' => 'image_url',
'required' => true
]);
这是我的控制器Save.php文件:
<?php
namespace Ultranoir\Slider\Controller\Adminhtml\SliderItem;
use Ultranoir\Slider\Model\Slider;
use Magento\Backend\App\Action;
use Magento\TestFramework\ErrorLog\Logger;
use Magento\Framework\App\Filesystem\DirectoryList;
class Save extends \Magento\Backend\App\Action
{
/**
* Store manager
*
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @var \Magento\Framework\Image\Factory
*/
protected $imageFactory;
/**
* @var \Magento\Framework\Image\Factory
*/
protected $mediaDirectory;
/**
* @var \Magento\Framework\View\Asset\Repository
*/
protected $assetRepo;
/**
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\Image\Factory $imageFactory
* @param \Magento\Framework\Filesystem $fileSystem
* @param \Magento\Framework\View\Asset\Repository $assetRepo
* @param Action\Context $context
*/
public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Image\Factory $imageFactory,
\Magento\Framework\Filesystem $fileSystem,
\Magento\Framework\View\Asset\Repository $assetRepo,
Action\Context $context)
{
$this->storeManager = $storeManager;
$this->imageFactory = $imageFactory;
/** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
$this->mediaDirectory = $fileSystem->getDirectoryRead(DirectoryList::MEDIA);
parent::__construct($context);
}
/**
* {@inheritdoc}
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ultranoir_Slider::save_slideritem');
}
/**
* Save action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$data = $this->getRequest()->getPostValue();
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
if ($data) {
/** @var \Ultranoir\Slider\Model\SliderItem $model */
$model = $this->_objectManager->create('\Ultranoir\Slider\Model\SliderItem');
$id = $this->getRequest()->getParam('slider_item_id');
if ($id) {
$model->load($id);
}
/** @var \Ultranoir\Slider\Model\Slider $slider */
$slider = $this->_objectManager->create('\Ultranoir\Slider\Model\Slider');
$slider->load($model->getSliderId());
try{
$data['image_url'] = $this->saveImage();
} catch (\Exception $e) {
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
$this->messageManager->addException($e, __('Something went wrong while uploading the file.'));
$this->_getSession()->setFormData($data);
return $resultRedirect->setPath('*/*/edit', ['slider_item_id' => $this->getRequest()->getParam
('slider_item_id')]);
}
$model->setData($data);
$this->_eventManager->dispatch(
'ultraslider_slideritem_prepare_save',
['slideritem' => $model, 'request' => $this->getRequest()]
);
try {
$model->save();
$this->messageManager->addSuccess(__('You saved this item.'));
$this->_objectManager->get('Magento\Backend\Model\Session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
return $resultRedirect->setPath('*/*/edit', ['slider_item_id' => $model->getId(), '_current' =>
true]);
}
return $resultRedirect->setPath('*/*/');
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\RuntimeException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addException($e, __('Something went wrong while saving the record.'));
}
$this->_getSession()->setFormData($data);
return $resultRedirect->setPath('*/*/edit', ['slider_item_id' => $this->getRequest()->getParam
('slider_item_id')]);
}
return $resultRedirect->setPath('*/*/');
}
protected function saveImage(){
$uploader = $this->_objectManager->create(
'Magento\MediaStorage\Model\File\Uploader',
['fileId' => 'image_url']
);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
/** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */
$imageAdapter = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')->create();
$uploader->addValidateCallback('ultraslider_slideritem_image', $imageAdapter, 'validateUploadFile');
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$result = $uploader->save($this->getBaseMediaPath());
$this->generateThumbnails($result['file'], $this->getBaseMediaPath());
$this->_eventManager->dispatch(
'ultraslider_slideritem_gallery_upload_image_after',
['result' => $result, 'action' => $this]
);
unset($result['tmp_name']);
unset($result['path']);
$result['url'] = $this->getBaseMediaUrl(). $result['file'];
return $result['url'];
}
protected function getBaseMediaPath(){
return $this->mediaDirectory->getAbsolutePath('slider/slideritem');
}
protected function getBaseMediaUrl(){
return $this->storeManager->getStore()->getBaseUrl(
\Magento\Framework\UrlInterface::URL_TYPE_MEDIA
).'slider/slideritem';
}
/**
* @return string
*/
public function getImageUrl($filePath)
{
if (!$this->mediaDirectory->isFile($filePath)) {
$url = $this->assetRepo->getUrl(
"Ultranoir_Slider::images/slideritem/placeholder/thumbnail.jpg"
);
} else {
$url = $this->storeManager->getStore()->getBaseUrl(
\Magento\Framework\UrlInterface::URL_TYPE_MEDIA
) . $filePath;
}
return $url;
}
public function generateThumbnails($fileName, $destinationBaseDir){
$configs = [
[
'width' => 100,
'height' => 100
],
[
'width' => 200,
'height' => 200
],
];
// build new filename (most important params)
foreach($configs as $config){
$processor = $this->imageFactory->create($destinationBaseDir.$fileName);
$processor->keepTransparency(true);
$processor->keepAspectRatio(true);
$processor->resize($config['width'], $config['height']);
$path = [
$destinationBaseDir,
'cache',
$this->storeManager->getStore()->getId(),
'thumbnail'
];
$path[] = "{$config['width']}x{$config['height']}";
$newFile = implode('/', $path) . $fileName;
$processor->save($newFile);
}
}
}
提前感谢您的回答。
答案 0 :(得分:0)
您需要根据操作更改保存代码。意味着新项目保存第一次或任何项目随时编辑。
您可以执行此类代码。
depth
答案 1 :(得分:0)
在保存数据之前,您需要将图像格式从数组更改为字符串。要解决此问题,只需在“$model->setData($data);
”文件中的“save.php
”之前插入以下代码即可。
代码是:
if(isset($data['image_url']['value']))
{
$data['image_url'] = $data['image_url']['value'];
}