0

How can I export a products with attributes of type "Fixed Product Tax"? I tried to create one on a product manually and export it, but nothing appeared in the generated CSV.
How can I achieve this? My controller code is here..

<?php

namespace Vendor\Extension\Controller\Adminhtml\Export;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Model\Product\Attribute\Repository as AttributeRepository;
use Magento\Catalog\Model\Product\Attribute\Source\Status as ProductStatus;
use Magento\Catalog\Model\Product\Visibility as ProductVisibility;
use Magento\Catalog\Api\Data\ProductInterface;

class Index extends Action
{
    protected $fileFactory;
    protected $productRepository;
    protected $scopeConfig;
    protected $storeManager;
    protected $searchCriteriaBuilder;
    protected $attributeRepository;

    public function __construct(
        Context $context,
        FileFactory $fileFactory,
        ProductRepositoryInterface $productRepository,
        ScopeConfigInterface $scopeConfig,
        StoreManagerInterface $storeManager,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        AttributeRepository $attributeRepository
    ) {
        parent::__construct($context);
        $this->fileFactory = $fileFactory;
        $this->productRepository = $productRepository;
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->attributeRepository = $attributeRepository;
    }

    public function execute()
    {
        $fileName = 'fixed_product_tax.csv';
        $content = $this->getCsvContent();

        return $this->fileFactory->create(
            $fileName,
            $content,
            \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR,
            'text/csv'
        );
    }

    protected function getCsvContent()
    {
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter(ProductInterface::STATUS, ProductStatus::STATUS_ENABLED)
            ->addFilter(ProductInterface::VISIBILITY, ProductVisibility::VISIBILITY_BOTH)
            ->create();

        $productCollection = $this->productRepository->getList($searchCriteria);

        $data = [];
        $data[] = ['SKU', 'Fixed Product Tax'];
        foreach ($productCollection->getItems() as $product) {
            $fixedProductTax = $this->getAttributeValue($product, 'aams_nicotina');
            $logger->info(print_r($fixedProductTax,true));
            $data[] = [$product->getSku(), $fixedProductTax];
        }

        $handle = fopen('php://memory', 'w');
        foreach ($data as $line) {
            fputcsv($handle, $line);
        }
        fseek($handle, 0);

        return stream_get_contents($handle);
    }

    protected function getAttributeValue($product, $attributeCode)
    {
        $attribute = $this->attributeRepository->get($attributeCode);

        if (!$attribute) {
            return '';
        }

        $attributeValue = $product->getData($attributeCode);

        // Example of processing if attribute returns an array
        if (is_array($attributeValue) && isset($attributeValue[0]['value'])) {
            return $attributeValue[0]['value'];
        }

        return $attributeValue;
    }
}

And Csv file is :- https://imgur.com/ZBEiDuF

1 Answer 1

0

Instead of using the attribute 'aams_nicotina', use 'name' in its place, and then provide me with the resulting CSV file. If name values prints fine then might be attriubte configuration issue.

then you have to change "Used in Product Listing" value to yes in atribute aams_nicotina.

After changing value do run bin/magento cache:flush

enter image description here

Do let me know if that solve your issue

Furtherly below is the script that i used which gave me right values for "brand" attribute in csv, you can try that too

<?php

use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Model\Product\Attribute\Repository as AttributeRepository;
use Magento\Catalog\Model\Product\Attribute\Source\Status as ProductStatus;
use Magento\Catalog\Model\Product\Visibility as ProductVisibility;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Catalog\Api\Data\ProductInterface;

// Include Magento's Bootstrap file
require '../../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');


error_reporting(E_ALL);
ini_set('display_errors', 1);

$fileFactory = $obj->get(\Magento\Framework\App\Response\Http\FileFactory::class);
$productRepository = $obj->get(ProductRepositoryInterface::class);
$scopeConfig = $obj->get(ScopeConfigInterface::class);
$storeManager = $obj->get(StoreManagerInterface::class);
$searchCriteriaBuilder = $obj->get(SearchCriteriaBuilder::class);
$attributeRepository = $obj->get(AttributeRepository::class);

$fileName = 'fixed_product_tax.csv';

$data = [];
$data[] = ['SKU', 'Fixed Product Tax']; // Header row

$searchCriteria = $searchCriteriaBuilder
    ->addFilter(ProductInterface::STATUS, ProductStatus::STATUS_ENABLED)
    ->addFilter(ProductInterface::VISIBILITY, ProductVisibility::VISIBILITY_BOTH)
    ->create();

$productCollection = $productRepository->getList($searchCriteria);

foreach ($productCollection->getItems() as $product) {
    $fixedProductTax = getAttributeValue($product, 'brand', $attributeRepository);
    $data[] = [$product->getSku(), $fixedProductTax];
}

// Write data to CSV
$csvFile = fopen($fileName, 'w');
foreach ($data as $line) {
    fputcsv($csvFile, $line);
}
fclose($csvFile);

echo "CSV Exported: " . $fileName . PHP_EOL;

/**
 * Get the attribute value for a product.
 *
 * @param \Magento\Catalog\Api\Data\ProductInterface $product
 * @param string $attributeCode
 * @param AttributeRepository $attributeRepository
 * @return mixed|string
 */
function getAttributeValue($product, $attributeCode, $attributeRepository)
{
    try {
        $attribute = $attributeRepository->get($attributeCode);
    } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
        return '';
    }

    if (!$attribute) {
        return '';
    }

    $attributeValue = $product->getData($attributeCode);

    // Process if the attribute value is an array
    if (is_array($attributeValue) && isset($attributeValue[0]['value'])) {
        return $attributeValue[0]['value'];
    }

    return $attributeValue;
}
2
  • @ Kareem that's working for me... Thanks.... Commented Jul 4 at 5:23
  • @KevalChauhan Glad it works, Happy coding :)
    – Kareem k
    Commented Jul 4 at 5:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.