there I'm trying to create a file upload attribute for a product this is what I have so far.
InstallSchema.php
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'my_attribute_image',
[
'type' => 'varchar',
'backend' => 'Vender\module\Model\Attribute\Product\Image',
'frontend' => '',
'label' => 'My Attribute Image',
'input' => 'image',
'class' => '',
'source' => '',
'group' =>'My custom group',
'visible' => true,
'required' => false,
'user_defined' => false,
'default' => 0,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => true,
'used_in_product_listing' => true,
'unique' => false,
'apply_to' => ''
]
);
Model\Attribute\Product\Image.php
use Magento\Framework\App\Filesystem\DirectoryList;
class Image extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
{
protected $_uploaderFactory;
protected $_filesystem;
protected $_fileUploaderFactory;
protected $_logger;
protected $httpFactory;
public function __construct(
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Filesystem $filesystem,
\Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
\Magento\Framework\HTTP\Adapter\FileTransferFactory $httpFactory
) {
$this->_filesystem = $filesystem;
$this->_fileUploaderFactory = $fileUploaderFactory;
$this->httpFactory = $httpFactory;
$this->_logger = $logger;
}
public function afterSave($object)
{
$attributeCode = $this->getAttribute()->getAttributeCode();
$image_name = $_FILES["product"]["name"]["my_attribute_image"];
$path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('ProductAttributes');
// add image name as attbute value
$object->setData($attributeCode , $image_name);
$this->getAttribute()->getEntity()->saveAttribute($object, $attributeCode);
try {
$uploader = $this->_fileUploaderFactory->create(['fileId' => $image_name]);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(true);
$result = $uploader->save($path);
} catch (\Exception $e) {
if ($e->getCode() != \Magento\MediaStorage\Model\File\Uploader::TMP_NAME_EMPTY) {
$this->_logger->critical($e);
echo "ERROR";
}
}
echo "<pre>";
print_r($_FILES);
echo "</pre>";
}
}
$attributeCode is returning the correct value
$image_name is returning the correct value
$path is not including the domain name but is from home/public_html/pub/media...
The image name is correctly stored in the database in catalog_product_entity_varchar
But the image doesn't save in the folder or anywhere I can see. No errors are thrown if i select an image but if i leave it empty error is echo
Please help