Magento 2 custom product image attribute save issue












1















Magento ver.: 2.2.2



I have created custom image attribute. This is displaying perfectly. But when I upload an image and save product, it's not saving. When I have debugged my code, I have found an issue. My image attribute value display null value every time in my model file(MagetestTestModelAttributeProductImage).



enter image description here



Here is my code.



app/code/Magetest/Test/Setup/InstallData.php



    <?php
namespace MagetestTestSetup;

use MagentoEavSetupEavSetupFactory;
use MagentoCatalogSetupCategorySetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{

protected $categorySetupFactory;

public function __construct(
MagentoCatalogSetupCategorySetupFactory $categorySetupFactory,
MagentoEavModelEntityTypeFactory $eavTypeFactory,
MagentoCatalogModelResourceModelEavAttributeFactory $attributeFactory,
MagentoEavModelEntityAttributeSetFactory $attributeSetFactory,
MagentoEavModelEntityAttributeGroupFactory $attributeGroupFactory,
MagentoEavModelAttributeManagement $attributeManagement,
MagentoEavSetupEavSetupFactory $eavSetupFactory,
MagentoEavModelResourceModelEntityAttributeGroupCollectionFactory $groupCollectionFactory
) {
$this->_categorySetupFactory = $categorySetupFactory;
$this->_eavTypeFactory = $eavTypeFactory;
$this->_attributeFactory = $attributeFactory;
$this->_attributeSetFactory = $attributeSetFactory;
$this->_attributeGroupFactory = $attributeGroupFactory;
$this->_attributeManagement = $attributeManagement;
$this->_eavSetupFactory = $eavSetupFactory;
$this->_groupCollectionFactory = $groupCollectionFactory;
}

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$groupName = 'Custom Product Image Upload';
$attributes = [
'custom_product_image' => [
'type' => 'varchar',
'backend' => 'MagetestTestModelAttributeProductImage',
'frontend' => '',
'label' => 'Upload Custom Image',
'input' => 'image',
'class' => '',
'group' => $groupName,
'source' => '',
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => null,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => false,
'unique' => false,
'apply_to' => '',
'is_used_in_grid' => false,
'is_visible_in_grid' => false,
'is_filterable_in_grid' => false
]
];

$categorySetup = $this->_categorySetupFactory->create(['setup' => $setup]);

foreach ($attributes as $code => $params)
$categorySetup->addAttribute(MagentoCatalogModelProduct::ENTITY, $code, $params);

$this->sortGroup($groupName, 11);
}

private function sortGroup($attributeGroupName, $order)
{
$entityType = $this->_eavTypeFactory->create()->loadByCode('catalog_product');
$setCollection = $this->_attributeSetFactory->create()->getCollection();
$setCollection->addFieldToFilter('entity_type_id', $entityType->getId());

foreach ($setCollection as $attributeSet)
{
$group = $this->_groupCollectionFactory->create()
->addFieldToFilter('attribute_set_id', $attributeSet->getId())
->addFieldToFilter('attribute_group_name', $attributeGroupName)
->getFirstItem()
->setSortOrder($order)
->save();
}

return true;
}
}


app/code/Magetest/Test/Model/Attribute/Product/Image.php



<?php
namespace MagetestTestModelAttributeProduct;

use MagentoFrameworkAppFilesystemDirectoryList;

class Image extends MagentoEavModelEntityAttributeBackendAbstractBackend
{

protected $_uploaderFactory;
protected $_filesystem;
protected $_fileUploaderFactory;
protected $_logger;

public function __construct(
PsrLogLoggerInterface $logger,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory
) {
$this->_filesystem = $filesystem;
$this->_fileUploaderFactory = $fileUploaderFactory;
$this->_logger = $logger;
}

public function beforeSave($object)
{
echo $this->getAttribute()->getName();
//Out Put: custom_product_image
echo '<br>';
var_dump($object->getData($this->getAttribute()->getName()));
//Out Put: NULL
var_dump($this->getAttribute()->getName() . '_additional_data');
//Out Put: NULL
var_dump($object->getData('name'));
//Out Put: string(16) "Joust Duffle Bag"
exit;
$value = $object->getData($this->getAttribute()->getName() . '_additional_data');

if (empty($value) && empty($_FILES)) {
return $this;
}

if (is_array($value) && !empty($value['delete'])) {
$object->setData($this->getAttribute()->getName(), '');
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
return $this;
}

$path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('catalog/product/');

try {

$uploader = $this->_fileUploaderFactory->create(['fileId' => $this->getAttribute()->getName()]);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(true);
$result = $uploader->save($path);

$object->setData($this->getAttribute()->getName(), $result['file']);
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
} catch (Exception $e) {
if ($e->getCode() != MagentoMediaStorageModelFileUploader::TMP_NAME_EMPTY) {
$this->_logger->critical($e);
}
}

return $this;
}
}









share|improve this question
















bumped to the homepage by Community 1 hour ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
















  • You can find answer to it here magento.stackexchange.com/questions/170186/…

    – Shireen N
    Feb 5 '18 at 9:23











  • @shireen Thanks for replay. It's display in "media image" section. I want to display image upload button in my custom section. Please check my screenshot for more detail.

    – Vithal Bariya
    Feb 5 '18 at 9:37











  • @Vithal Bariya any other files used or not, if used share code.

    – Suresh Chikani
    Feb 5 '18 at 12:18











  • @SureshChikani Other file is not used, Only use basic module required file like registration.php , Data.php, module.xml etc.

    – Vithal Bariya
    Feb 5 '18 at 13:03


















1















Magento ver.: 2.2.2



I have created custom image attribute. This is displaying perfectly. But when I upload an image and save product, it's not saving. When I have debugged my code, I have found an issue. My image attribute value display null value every time in my model file(MagetestTestModelAttributeProductImage).



enter image description here



Here is my code.



app/code/Magetest/Test/Setup/InstallData.php



    <?php
namespace MagetestTestSetup;

use MagentoEavSetupEavSetupFactory;
use MagentoCatalogSetupCategorySetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{

protected $categorySetupFactory;

public function __construct(
MagentoCatalogSetupCategorySetupFactory $categorySetupFactory,
MagentoEavModelEntityTypeFactory $eavTypeFactory,
MagentoCatalogModelResourceModelEavAttributeFactory $attributeFactory,
MagentoEavModelEntityAttributeSetFactory $attributeSetFactory,
MagentoEavModelEntityAttributeGroupFactory $attributeGroupFactory,
MagentoEavModelAttributeManagement $attributeManagement,
MagentoEavSetupEavSetupFactory $eavSetupFactory,
MagentoEavModelResourceModelEntityAttributeGroupCollectionFactory $groupCollectionFactory
) {
$this->_categorySetupFactory = $categorySetupFactory;
$this->_eavTypeFactory = $eavTypeFactory;
$this->_attributeFactory = $attributeFactory;
$this->_attributeSetFactory = $attributeSetFactory;
$this->_attributeGroupFactory = $attributeGroupFactory;
$this->_attributeManagement = $attributeManagement;
$this->_eavSetupFactory = $eavSetupFactory;
$this->_groupCollectionFactory = $groupCollectionFactory;
}

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$groupName = 'Custom Product Image Upload';
$attributes = [
'custom_product_image' => [
'type' => 'varchar',
'backend' => 'MagetestTestModelAttributeProductImage',
'frontend' => '',
'label' => 'Upload Custom Image',
'input' => 'image',
'class' => '',
'group' => $groupName,
'source' => '',
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => null,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => false,
'unique' => false,
'apply_to' => '',
'is_used_in_grid' => false,
'is_visible_in_grid' => false,
'is_filterable_in_grid' => false
]
];

$categorySetup = $this->_categorySetupFactory->create(['setup' => $setup]);

foreach ($attributes as $code => $params)
$categorySetup->addAttribute(MagentoCatalogModelProduct::ENTITY, $code, $params);

$this->sortGroup($groupName, 11);
}

private function sortGroup($attributeGroupName, $order)
{
$entityType = $this->_eavTypeFactory->create()->loadByCode('catalog_product');
$setCollection = $this->_attributeSetFactory->create()->getCollection();
$setCollection->addFieldToFilter('entity_type_id', $entityType->getId());

foreach ($setCollection as $attributeSet)
{
$group = $this->_groupCollectionFactory->create()
->addFieldToFilter('attribute_set_id', $attributeSet->getId())
->addFieldToFilter('attribute_group_name', $attributeGroupName)
->getFirstItem()
->setSortOrder($order)
->save();
}

return true;
}
}


app/code/Magetest/Test/Model/Attribute/Product/Image.php



<?php
namespace MagetestTestModelAttributeProduct;

use MagentoFrameworkAppFilesystemDirectoryList;

class Image extends MagentoEavModelEntityAttributeBackendAbstractBackend
{

protected $_uploaderFactory;
protected $_filesystem;
protected $_fileUploaderFactory;
protected $_logger;

public function __construct(
PsrLogLoggerInterface $logger,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory
) {
$this->_filesystem = $filesystem;
$this->_fileUploaderFactory = $fileUploaderFactory;
$this->_logger = $logger;
}

public function beforeSave($object)
{
echo $this->getAttribute()->getName();
//Out Put: custom_product_image
echo '<br>';
var_dump($object->getData($this->getAttribute()->getName()));
//Out Put: NULL
var_dump($this->getAttribute()->getName() . '_additional_data');
//Out Put: NULL
var_dump($object->getData('name'));
//Out Put: string(16) "Joust Duffle Bag"
exit;
$value = $object->getData($this->getAttribute()->getName() . '_additional_data');

if (empty($value) && empty($_FILES)) {
return $this;
}

if (is_array($value) && !empty($value['delete'])) {
$object->setData($this->getAttribute()->getName(), '');
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
return $this;
}

$path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('catalog/product/');

try {

$uploader = $this->_fileUploaderFactory->create(['fileId' => $this->getAttribute()->getName()]);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(true);
$result = $uploader->save($path);

$object->setData($this->getAttribute()->getName(), $result['file']);
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
} catch (Exception $e) {
if ($e->getCode() != MagentoMediaStorageModelFileUploader::TMP_NAME_EMPTY) {
$this->_logger->critical($e);
}
}

return $this;
}
}









share|improve this question
















bumped to the homepage by Community 1 hour ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
















  • You can find answer to it here magento.stackexchange.com/questions/170186/…

    – Shireen N
    Feb 5 '18 at 9:23











  • @shireen Thanks for replay. It's display in "media image" section. I want to display image upload button in my custom section. Please check my screenshot for more detail.

    – Vithal Bariya
    Feb 5 '18 at 9:37











  • @Vithal Bariya any other files used or not, if used share code.

    – Suresh Chikani
    Feb 5 '18 at 12:18











  • @SureshChikani Other file is not used, Only use basic module required file like registration.php , Data.php, module.xml etc.

    – Vithal Bariya
    Feb 5 '18 at 13:03
















1












1








1








Magento ver.: 2.2.2



I have created custom image attribute. This is displaying perfectly. But when I upload an image and save product, it's not saving. When I have debugged my code, I have found an issue. My image attribute value display null value every time in my model file(MagetestTestModelAttributeProductImage).



enter image description here



Here is my code.



app/code/Magetest/Test/Setup/InstallData.php



    <?php
namespace MagetestTestSetup;

use MagentoEavSetupEavSetupFactory;
use MagentoCatalogSetupCategorySetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{

protected $categorySetupFactory;

public function __construct(
MagentoCatalogSetupCategorySetupFactory $categorySetupFactory,
MagentoEavModelEntityTypeFactory $eavTypeFactory,
MagentoCatalogModelResourceModelEavAttributeFactory $attributeFactory,
MagentoEavModelEntityAttributeSetFactory $attributeSetFactory,
MagentoEavModelEntityAttributeGroupFactory $attributeGroupFactory,
MagentoEavModelAttributeManagement $attributeManagement,
MagentoEavSetupEavSetupFactory $eavSetupFactory,
MagentoEavModelResourceModelEntityAttributeGroupCollectionFactory $groupCollectionFactory
) {
$this->_categorySetupFactory = $categorySetupFactory;
$this->_eavTypeFactory = $eavTypeFactory;
$this->_attributeFactory = $attributeFactory;
$this->_attributeSetFactory = $attributeSetFactory;
$this->_attributeGroupFactory = $attributeGroupFactory;
$this->_attributeManagement = $attributeManagement;
$this->_eavSetupFactory = $eavSetupFactory;
$this->_groupCollectionFactory = $groupCollectionFactory;
}

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$groupName = 'Custom Product Image Upload';
$attributes = [
'custom_product_image' => [
'type' => 'varchar',
'backend' => 'MagetestTestModelAttributeProductImage',
'frontend' => '',
'label' => 'Upload Custom Image',
'input' => 'image',
'class' => '',
'group' => $groupName,
'source' => '',
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => null,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => false,
'unique' => false,
'apply_to' => '',
'is_used_in_grid' => false,
'is_visible_in_grid' => false,
'is_filterable_in_grid' => false
]
];

$categorySetup = $this->_categorySetupFactory->create(['setup' => $setup]);

foreach ($attributes as $code => $params)
$categorySetup->addAttribute(MagentoCatalogModelProduct::ENTITY, $code, $params);

$this->sortGroup($groupName, 11);
}

private function sortGroup($attributeGroupName, $order)
{
$entityType = $this->_eavTypeFactory->create()->loadByCode('catalog_product');
$setCollection = $this->_attributeSetFactory->create()->getCollection();
$setCollection->addFieldToFilter('entity_type_id', $entityType->getId());

foreach ($setCollection as $attributeSet)
{
$group = $this->_groupCollectionFactory->create()
->addFieldToFilter('attribute_set_id', $attributeSet->getId())
->addFieldToFilter('attribute_group_name', $attributeGroupName)
->getFirstItem()
->setSortOrder($order)
->save();
}

return true;
}
}


app/code/Magetest/Test/Model/Attribute/Product/Image.php



<?php
namespace MagetestTestModelAttributeProduct;

use MagentoFrameworkAppFilesystemDirectoryList;

class Image extends MagentoEavModelEntityAttributeBackendAbstractBackend
{

protected $_uploaderFactory;
protected $_filesystem;
protected $_fileUploaderFactory;
protected $_logger;

public function __construct(
PsrLogLoggerInterface $logger,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory
) {
$this->_filesystem = $filesystem;
$this->_fileUploaderFactory = $fileUploaderFactory;
$this->_logger = $logger;
}

public function beforeSave($object)
{
echo $this->getAttribute()->getName();
//Out Put: custom_product_image
echo '<br>';
var_dump($object->getData($this->getAttribute()->getName()));
//Out Put: NULL
var_dump($this->getAttribute()->getName() . '_additional_data');
//Out Put: NULL
var_dump($object->getData('name'));
//Out Put: string(16) "Joust Duffle Bag"
exit;
$value = $object->getData($this->getAttribute()->getName() . '_additional_data');

if (empty($value) && empty($_FILES)) {
return $this;
}

if (is_array($value) && !empty($value['delete'])) {
$object->setData($this->getAttribute()->getName(), '');
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
return $this;
}

$path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('catalog/product/');

try {

$uploader = $this->_fileUploaderFactory->create(['fileId' => $this->getAttribute()->getName()]);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(true);
$result = $uploader->save($path);

$object->setData($this->getAttribute()->getName(), $result['file']);
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
} catch (Exception $e) {
if ($e->getCode() != MagentoMediaStorageModelFileUploader::TMP_NAME_EMPTY) {
$this->_logger->critical($e);
}
}

return $this;
}
}









share|improve this question
















Magento ver.: 2.2.2



I have created custom image attribute. This is displaying perfectly. But when I upload an image and save product, it's not saving. When I have debugged my code, I have found an issue. My image attribute value display null value every time in my model file(MagetestTestModelAttributeProductImage).



enter image description here



Here is my code.



app/code/Magetest/Test/Setup/InstallData.php



    <?php
namespace MagetestTestSetup;

use MagentoEavSetupEavSetupFactory;
use MagentoCatalogSetupCategorySetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{

protected $categorySetupFactory;

public function __construct(
MagentoCatalogSetupCategorySetupFactory $categorySetupFactory,
MagentoEavModelEntityTypeFactory $eavTypeFactory,
MagentoCatalogModelResourceModelEavAttributeFactory $attributeFactory,
MagentoEavModelEntityAttributeSetFactory $attributeSetFactory,
MagentoEavModelEntityAttributeGroupFactory $attributeGroupFactory,
MagentoEavModelAttributeManagement $attributeManagement,
MagentoEavSetupEavSetupFactory $eavSetupFactory,
MagentoEavModelResourceModelEntityAttributeGroupCollectionFactory $groupCollectionFactory
) {
$this->_categorySetupFactory = $categorySetupFactory;
$this->_eavTypeFactory = $eavTypeFactory;
$this->_attributeFactory = $attributeFactory;
$this->_attributeSetFactory = $attributeSetFactory;
$this->_attributeGroupFactory = $attributeGroupFactory;
$this->_attributeManagement = $attributeManagement;
$this->_eavSetupFactory = $eavSetupFactory;
$this->_groupCollectionFactory = $groupCollectionFactory;
}

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$groupName = 'Custom Product Image Upload';
$attributes = [
'custom_product_image' => [
'type' => 'varchar',
'backend' => 'MagetestTestModelAttributeProductImage',
'frontend' => '',
'label' => 'Upload Custom Image',
'input' => 'image',
'class' => '',
'group' => $groupName,
'source' => '',
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => null,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => false,
'unique' => false,
'apply_to' => '',
'is_used_in_grid' => false,
'is_visible_in_grid' => false,
'is_filterable_in_grid' => false
]
];

$categorySetup = $this->_categorySetupFactory->create(['setup' => $setup]);

foreach ($attributes as $code => $params)
$categorySetup->addAttribute(MagentoCatalogModelProduct::ENTITY, $code, $params);

$this->sortGroup($groupName, 11);
}

private function sortGroup($attributeGroupName, $order)
{
$entityType = $this->_eavTypeFactory->create()->loadByCode('catalog_product');
$setCollection = $this->_attributeSetFactory->create()->getCollection();
$setCollection->addFieldToFilter('entity_type_id', $entityType->getId());

foreach ($setCollection as $attributeSet)
{
$group = $this->_groupCollectionFactory->create()
->addFieldToFilter('attribute_set_id', $attributeSet->getId())
->addFieldToFilter('attribute_group_name', $attributeGroupName)
->getFirstItem()
->setSortOrder($order)
->save();
}

return true;
}
}


app/code/Magetest/Test/Model/Attribute/Product/Image.php



<?php
namespace MagetestTestModelAttributeProduct;

use MagentoFrameworkAppFilesystemDirectoryList;

class Image extends MagentoEavModelEntityAttributeBackendAbstractBackend
{

protected $_uploaderFactory;
protected $_filesystem;
protected $_fileUploaderFactory;
protected $_logger;

public function __construct(
PsrLogLoggerInterface $logger,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory
) {
$this->_filesystem = $filesystem;
$this->_fileUploaderFactory = $fileUploaderFactory;
$this->_logger = $logger;
}

public function beforeSave($object)
{
echo $this->getAttribute()->getName();
//Out Put: custom_product_image
echo '<br>';
var_dump($object->getData($this->getAttribute()->getName()));
//Out Put: NULL
var_dump($this->getAttribute()->getName() . '_additional_data');
//Out Put: NULL
var_dump($object->getData('name'));
//Out Put: string(16) "Joust Duffle Bag"
exit;
$value = $object->getData($this->getAttribute()->getName() . '_additional_data');

if (empty($value) && empty($_FILES)) {
return $this;
}

if (is_array($value) && !empty($value['delete'])) {
$object->setData($this->getAttribute()->getName(), '');
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
return $this;
}

$path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('catalog/product/');

try {

$uploader = $this->_fileUploaderFactory->create(['fileId' => $this->getAttribute()->getName()]);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(true);
$result = $uploader->save($path);

$object->setData($this->getAttribute()->getName(), $result['file']);
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());
} catch (Exception $e) {
if ($e->getCode() != MagentoMediaStorageModelFileUploader::TMP_NAME_EMPTY) {
$this->_logger->critical($e);
}
}

return $this;
}
}






magento2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 5 '18 at 9:13









Navin Bhudiya

7381024




7381024










asked Feb 5 '18 at 8:48









Vithal BariyaVithal Bariya

471216




471216





bumped to the homepage by Community 1 hour ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 1 hour ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • You can find answer to it here magento.stackexchange.com/questions/170186/…

    – Shireen N
    Feb 5 '18 at 9:23











  • @shireen Thanks for replay. It's display in "media image" section. I want to display image upload button in my custom section. Please check my screenshot for more detail.

    – Vithal Bariya
    Feb 5 '18 at 9:37











  • @Vithal Bariya any other files used or not, if used share code.

    – Suresh Chikani
    Feb 5 '18 at 12:18











  • @SureshChikani Other file is not used, Only use basic module required file like registration.php , Data.php, module.xml etc.

    – Vithal Bariya
    Feb 5 '18 at 13:03





















  • You can find answer to it here magento.stackexchange.com/questions/170186/…

    – Shireen N
    Feb 5 '18 at 9:23











  • @shireen Thanks for replay. It's display in "media image" section. I want to display image upload button in my custom section. Please check my screenshot for more detail.

    – Vithal Bariya
    Feb 5 '18 at 9:37











  • @Vithal Bariya any other files used or not, if used share code.

    – Suresh Chikani
    Feb 5 '18 at 12:18











  • @SureshChikani Other file is not used, Only use basic module required file like registration.php , Data.php, module.xml etc.

    – Vithal Bariya
    Feb 5 '18 at 13:03



















You can find answer to it here magento.stackexchange.com/questions/170186/…

– Shireen N
Feb 5 '18 at 9:23





You can find answer to it here magento.stackexchange.com/questions/170186/…

– Shireen N
Feb 5 '18 at 9:23













@shireen Thanks for replay. It's display in "media image" section. I want to display image upload button in my custom section. Please check my screenshot for more detail.

– Vithal Bariya
Feb 5 '18 at 9:37





@shireen Thanks for replay. It's display in "media image" section. I want to display image upload button in my custom section. Please check my screenshot for more detail.

– Vithal Bariya
Feb 5 '18 at 9:37













@Vithal Bariya any other files used or not, if used share code.

– Suresh Chikani
Feb 5 '18 at 12:18





@Vithal Bariya any other files used or not, if used share code.

– Suresh Chikani
Feb 5 '18 at 12:18













@SureshChikani Other file is not used, Only use basic module required file like registration.php , Data.php, module.xml etc.

– Vithal Bariya
Feb 5 '18 at 13:03







@SureshChikani Other file is not used, Only use basic module required file like registration.php , Data.php, module.xml etc.

– Vithal Bariya
Feb 5 '18 at 13:03












1 Answer
1






active

oldest

votes


















0














I believe you are missing the upload action. Check with below steps if anything you have missed.



Step:-1



Create a InstallData.php file on location vendorModuleSetup



<?php
namespace VendorModuleSetup;

use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoEavModelEntityAttributeScopedAttributeInterface;

/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* EAV setup factory.
*
* @var EavSetupFactory
*/
private $_eavSetupFactory;
protected $categorySetupFactory;

/**
* Init.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory, MagentoCatalogSetupCategorySetupFactory $categorySetupFactory)
{
$this->_eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
}

/**
* {@inheritdoc}
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
/** @var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
MagentoCatalogModelProduct::ENTITY, 'custom_image', [
'type' => 'varchar',
'label' => 'Custom Image',
'input' => 'image',
'backend' => 'MagentoCatalogModelProductAttributeBackendImage',
'required' => false,
'sort_order' => 9,
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
}
}


Step:-2



Create a product_form.xml file on location PackageCustom_Moduleviewadminhtmlui_component



<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="content">
<field name="custom_image">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="source" xsi:type="string">category</item>
<item name="label" xsi:type="string" translate="true">Custom Image</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="formElement" xsi:type="string">fileUploader</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
<item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
<item name="required" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">40</item>
<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="module/product_image/upload"/>
</item>
</item>
</argument>
</field>
</fieldset>
</form>


Step:-3



Add below code in Vendor/Module/etc/di.xml



<type name="VendorModuleControllerAdminhtmlProductImageUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">MagentoCatalogProductImageUpload</argument>
</arguments>
</type>
<virtualType name="MagentoCatalogProductImageUpload" type="MagentoCatalogModelImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">catalog/tmp/product</argument>
<argument name="basePath" xsi:type="string">catalog/product</argument>
<argument name="allowedExtensions" xsi:type="array">
<item name="jpg" xsi:type="string">jpg</item>
<item name="jpeg" xsi:type="string">jpeg</item>
<item name="gif" xsi:type="string">gif</item>
<item name="png" xsi:type="string">png</item>
</argument>
</arguments>
</virtualType>


Step:-4



Create Upload.php file on location Vendor/Module/Controller/Adminhtml/Product/Image



<?php
namespace VendorModuleControllerAdminhtmlProductImage;

use MagentoFrameworkControllerResultFactory;

/**
* Adminhtml Product Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
{
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;

/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;

/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;

/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;

/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;

/**
* @var PsrLogLoggerInterface
*/
protected $logger;

/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
) {
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
}

/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Vendor_Module::product');
}

/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
{
try {
$result = $this->imageUploader->saveFileToTmpDir('custom_image');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
} catch (Exception $e) {
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
}
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}
}


Try if this helps you!






share|improve this answer
























  • Hello Shireen, Thanks for help. I have try your code But it's not working. Image not saved.

    – Vithal Bariya
    Feb 5 '18 at 11:18











Your Answer








StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "479"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f212217%2fmagento-2-custom-product-image-attribute-save-issue%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














I believe you are missing the upload action. Check with below steps if anything you have missed.



Step:-1



Create a InstallData.php file on location vendorModuleSetup



<?php
namespace VendorModuleSetup;

use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoEavModelEntityAttributeScopedAttributeInterface;

/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* EAV setup factory.
*
* @var EavSetupFactory
*/
private $_eavSetupFactory;
protected $categorySetupFactory;

/**
* Init.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory, MagentoCatalogSetupCategorySetupFactory $categorySetupFactory)
{
$this->_eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
}

/**
* {@inheritdoc}
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
/** @var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
MagentoCatalogModelProduct::ENTITY, 'custom_image', [
'type' => 'varchar',
'label' => 'Custom Image',
'input' => 'image',
'backend' => 'MagentoCatalogModelProductAttributeBackendImage',
'required' => false,
'sort_order' => 9,
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
}
}


Step:-2



Create a product_form.xml file on location PackageCustom_Moduleviewadminhtmlui_component



<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="content">
<field name="custom_image">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="source" xsi:type="string">category</item>
<item name="label" xsi:type="string" translate="true">Custom Image</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="formElement" xsi:type="string">fileUploader</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
<item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
<item name="required" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">40</item>
<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="module/product_image/upload"/>
</item>
</item>
</argument>
</field>
</fieldset>
</form>


Step:-3



Add below code in Vendor/Module/etc/di.xml



<type name="VendorModuleControllerAdminhtmlProductImageUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">MagentoCatalogProductImageUpload</argument>
</arguments>
</type>
<virtualType name="MagentoCatalogProductImageUpload" type="MagentoCatalogModelImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">catalog/tmp/product</argument>
<argument name="basePath" xsi:type="string">catalog/product</argument>
<argument name="allowedExtensions" xsi:type="array">
<item name="jpg" xsi:type="string">jpg</item>
<item name="jpeg" xsi:type="string">jpeg</item>
<item name="gif" xsi:type="string">gif</item>
<item name="png" xsi:type="string">png</item>
</argument>
</arguments>
</virtualType>


Step:-4



Create Upload.php file on location Vendor/Module/Controller/Adminhtml/Product/Image



<?php
namespace VendorModuleControllerAdminhtmlProductImage;

use MagentoFrameworkControllerResultFactory;

/**
* Adminhtml Product Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
{
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;

/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;

/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;

/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;

/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;

/**
* @var PsrLogLoggerInterface
*/
protected $logger;

/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
) {
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
}

/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Vendor_Module::product');
}

/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
{
try {
$result = $this->imageUploader->saveFileToTmpDir('custom_image');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
} catch (Exception $e) {
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
}
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}
}


Try if this helps you!






share|improve this answer
























  • Hello Shireen, Thanks for help. I have try your code But it's not working. Image not saved.

    – Vithal Bariya
    Feb 5 '18 at 11:18
















0














I believe you are missing the upload action. Check with below steps if anything you have missed.



Step:-1



Create a InstallData.php file on location vendorModuleSetup



<?php
namespace VendorModuleSetup;

use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoEavModelEntityAttributeScopedAttributeInterface;

/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* EAV setup factory.
*
* @var EavSetupFactory
*/
private $_eavSetupFactory;
protected $categorySetupFactory;

/**
* Init.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory, MagentoCatalogSetupCategorySetupFactory $categorySetupFactory)
{
$this->_eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
}

/**
* {@inheritdoc}
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
/** @var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
MagentoCatalogModelProduct::ENTITY, 'custom_image', [
'type' => 'varchar',
'label' => 'Custom Image',
'input' => 'image',
'backend' => 'MagentoCatalogModelProductAttributeBackendImage',
'required' => false,
'sort_order' => 9,
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
}
}


Step:-2



Create a product_form.xml file on location PackageCustom_Moduleviewadminhtmlui_component



<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="content">
<field name="custom_image">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="source" xsi:type="string">category</item>
<item name="label" xsi:type="string" translate="true">Custom Image</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="formElement" xsi:type="string">fileUploader</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
<item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
<item name="required" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">40</item>
<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="module/product_image/upload"/>
</item>
</item>
</argument>
</field>
</fieldset>
</form>


Step:-3



Add below code in Vendor/Module/etc/di.xml



<type name="VendorModuleControllerAdminhtmlProductImageUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">MagentoCatalogProductImageUpload</argument>
</arguments>
</type>
<virtualType name="MagentoCatalogProductImageUpload" type="MagentoCatalogModelImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">catalog/tmp/product</argument>
<argument name="basePath" xsi:type="string">catalog/product</argument>
<argument name="allowedExtensions" xsi:type="array">
<item name="jpg" xsi:type="string">jpg</item>
<item name="jpeg" xsi:type="string">jpeg</item>
<item name="gif" xsi:type="string">gif</item>
<item name="png" xsi:type="string">png</item>
</argument>
</arguments>
</virtualType>


Step:-4



Create Upload.php file on location Vendor/Module/Controller/Adminhtml/Product/Image



<?php
namespace VendorModuleControllerAdminhtmlProductImage;

use MagentoFrameworkControllerResultFactory;

/**
* Adminhtml Product Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
{
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;

/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;

/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;

/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;

/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;

/**
* @var PsrLogLoggerInterface
*/
protected $logger;

/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
) {
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
}

/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Vendor_Module::product');
}

/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
{
try {
$result = $this->imageUploader->saveFileToTmpDir('custom_image');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
} catch (Exception $e) {
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
}
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}
}


Try if this helps you!






share|improve this answer
























  • Hello Shireen, Thanks for help. I have try your code But it's not working. Image not saved.

    – Vithal Bariya
    Feb 5 '18 at 11:18














0












0








0







I believe you are missing the upload action. Check with below steps if anything you have missed.



Step:-1



Create a InstallData.php file on location vendorModuleSetup



<?php
namespace VendorModuleSetup;

use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoEavModelEntityAttributeScopedAttributeInterface;

/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* EAV setup factory.
*
* @var EavSetupFactory
*/
private $_eavSetupFactory;
protected $categorySetupFactory;

/**
* Init.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory, MagentoCatalogSetupCategorySetupFactory $categorySetupFactory)
{
$this->_eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
}

/**
* {@inheritdoc}
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
/** @var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
MagentoCatalogModelProduct::ENTITY, 'custom_image', [
'type' => 'varchar',
'label' => 'Custom Image',
'input' => 'image',
'backend' => 'MagentoCatalogModelProductAttributeBackendImage',
'required' => false,
'sort_order' => 9,
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
}
}


Step:-2



Create a product_form.xml file on location PackageCustom_Moduleviewadminhtmlui_component



<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="content">
<field name="custom_image">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="source" xsi:type="string">category</item>
<item name="label" xsi:type="string" translate="true">Custom Image</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="formElement" xsi:type="string">fileUploader</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
<item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
<item name="required" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">40</item>
<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="module/product_image/upload"/>
</item>
</item>
</argument>
</field>
</fieldset>
</form>


Step:-3



Add below code in Vendor/Module/etc/di.xml



<type name="VendorModuleControllerAdminhtmlProductImageUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">MagentoCatalogProductImageUpload</argument>
</arguments>
</type>
<virtualType name="MagentoCatalogProductImageUpload" type="MagentoCatalogModelImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">catalog/tmp/product</argument>
<argument name="basePath" xsi:type="string">catalog/product</argument>
<argument name="allowedExtensions" xsi:type="array">
<item name="jpg" xsi:type="string">jpg</item>
<item name="jpeg" xsi:type="string">jpeg</item>
<item name="gif" xsi:type="string">gif</item>
<item name="png" xsi:type="string">png</item>
</argument>
</arguments>
</virtualType>


Step:-4



Create Upload.php file on location Vendor/Module/Controller/Adminhtml/Product/Image



<?php
namespace VendorModuleControllerAdminhtmlProductImage;

use MagentoFrameworkControllerResultFactory;

/**
* Adminhtml Product Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
{
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;

/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;

/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;

/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;

/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;

/**
* @var PsrLogLoggerInterface
*/
protected $logger;

/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
) {
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
}

/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Vendor_Module::product');
}

/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
{
try {
$result = $this->imageUploader->saveFileToTmpDir('custom_image');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
} catch (Exception $e) {
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
}
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}
}


Try if this helps you!






share|improve this answer













I believe you are missing the upload action. Check with below steps if anything you have missed.



Step:-1



Create a InstallData.php file on location vendorModuleSetup



<?php
namespace VendorModuleSetup;

use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoEavModelEntityAttributeScopedAttributeInterface;

/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* EAV setup factory.
*
* @var EavSetupFactory
*/
private $_eavSetupFactory;
protected $categorySetupFactory;

/**
* Init.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory, MagentoCatalogSetupCategorySetupFactory $categorySetupFactory)
{
$this->_eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
}

/**
* {@inheritdoc}
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
/** @var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
MagentoCatalogModelProduct::ENTITY, 'custom_image', [
'type' => 'varchar',
'label' => 'Custom Image',
'input' => 'image',
'backend' => 'MagentoCatalogModelProductAttributeBackendImage',
'required' => false,
'sort_order' => 9,
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
}
}


Step:-2



Create a product_form.xml file on location PackageCustom_Moduleviewadminhtmlui_component



<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="content">
<field name="custom_image">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="source" xsi:type="string">category</item>
<item name="label" xsi:type="string" translate="true">Custom Image</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="formElement" xsi:type="string">fileUploader</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
<item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
<item name="required" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">40</item>
<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="module/product_image/upload"/>
</item>
</item>
</argument>
</field>
</fieldset>
</form>


Step:-3



Add below code in Vendor/Module/etc/di.xml



<type name="VendorModuleControllerAdminhtmlProductImageUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">MagentoCatalogProductImageUpload</argument>
</arguments>
</type>
<virtualType name="MagentoCatalogProductImageUpload" type="MagentoCatalogModelImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">catalog/tmp/product</argument>
<argument name="basePath" xsi:type="string">catalog/product</argument>
<argument name="allowedExtensions" xsi:type="array">
<item name="jpg" xsi:type="string">jpg</item>
<item name="jpeg" xsi:type="string">jpeg</item>
<item name="gif" xsi:type="string">gif</item>
<item name="png" xsi:type="string">png</item>
</argument>
</arguments>
</virtualType>


Step:-4



Create Upload.php file on location Vendor/Module/Controller/Adminhtml/Product/Image



<?php
namespace VendorModuleControllerAdminhtmlProductImage;

use MagentoFrameworkControllerResultFactory;

/**
* Adminhtml Product Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
{
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;

/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;

/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;

/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;

/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;

/**
* @var PsrLogLoggerInterface
*/
protected $logger;

/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
) {
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
}

/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Vendor_Module::product');
}

/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
{
try {
$result = $this->imageUploader->saveFileToTmpDir('custom_image');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
} catch (Exception $e) {
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
}
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}
}


Try if this helps you!







share|improve this answer












share|improve this answer



share|improve this answer










answered Feb 5 '18 at 9:56









Shireen NShireen N

662411




662411













  • Hello Shireen, Thanks for help. I have try your code But it's not working. Image not saved.

    – Vithal Bariya
    Feb 5 '18 at 11:18



















  • Hello Shireen, Thanks for help. I have try your code But it's not working. Image not saved.

    – Vithal Bariya
    Feb 5 '18 at 11:18

















Hello Shireen, Thanks for help. I have try your code But it's not working. Image not saved.

– Vithal Bariya
Feb 5 '18 at 11:18





Hello Shireen, Thanks for help. I have try your code But it's not working. Image not saved.

– Vithal Bariya
Feb 5 '18 at 11:18


















draft saved

draft discarded




















































Thanks for contributing an answer to Magento Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f212217%2fmagento-2-custom-product-image-attribute-save-issue%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Polycentropodidae

Magento 2 Error message: Invalid state change requested

Paulmy