1

I wrote update quantity product by SKU, but I also want to update quantity product by name. Only update by SKU or name. Look my form <3

My form

enter image description here

My controller

public function execute()
{
    $data = $this->getRequest()->getParams();
    $sku = $data['sku'];
    $qty = $data['qty'];
    try {
        $productId = $this->product->getIdBySku($sku);
        $product = $this->product->load($productId);
        $stockItem = $this->_stockRegistry->getStockItemBySku($product->getSku());
        $stockItem->setQty($qty);
        $stockItem->save();
        $response["success"] = $this->_view->getLayout()
        ->createBlock('Vendor_Name\Module_Name\Block\Adminhtml\Ajax\Popup')
        ->setProduct($product)
        ->setQty($qty)
            ->setSku($sku)
            ->toHtml();
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($response);
        return $resultJson;
    }
    catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
        $response["error"] = $this->_view->getLayout()
        ->createBlock('Vendor_Name\Module_Name\Block\Adminhtml\Ajax\Popup')
        ->setProduct($product)
        ->setQty($qty)
            ->setSku($sku)
            ->toHtml();
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($response);
        return $resultJson;
    }
}

Please Help Me!

UPDATE

I saved data by SKU and name <3. but my popup not show. I want to show if the popup is successful, fail to show the error popup

$data = $this->getRequest()->getParams(); // lấy dữ liệu
    $attr = $data['attr'];
    $qty = $data['qty'];
    $select = $data['select'];
    // save by name
    if ($select == 'name') {
        $filterName = $this->filterBuilder->setField('name')->setValue($attr)->create();
        $searchCriteriaBuilder = $this->searchCriteriaBuilderFactory->create();
        $searchCriteriaBuilder->addFilters([$filterName]);
        $searchCriteria = $searchCriteriaBuilder->create();
        $products = $this->productRepository->getList($searchCriteria)->getItems();
        foreach ($products as $product) {
            $productName = $product->getName();
            $productSku = $product->getSku();
            $productId = $this->product->getIdBySku($productSku);
            $product = $this->product->load($productId);
            $stockItem = $this->stockRegistry->getStockItemBySku($product->getSku());
            if($productName == $attr){
                $stockItem->setQty($qty);
                $stockItem->save();
                $response["success"] = $this->_view->getLayout()
                ->createBlock('Vendor_Name\Module_Name\Block\Adminhtml\Ajax\Popup')
                ->setProduct($product)
                ->setQty($qty)
                    ->setAttr($attr)
                    ->toHtml();
                $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
                $resultJson->setData($response);
                return $resultJson;
            }else{
                $response["error"] = $this->_view->getLayout()
                ->createBlock('Vendor_Name\Module_Name\Block\Adminhtml\Ajax\Popup')
                ->setProduct($product)
                ->setQty($qty)
                    ->setSku($attr)
                    ->toHtml();
                $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
                $resultJson->setData($response);
                return $resultJson;
            }
        }
        // save by sku
    } else if ($select == 'sku') {
        $filterSku = $this->filterBuilder->setField('sku')->setValue($attr)->create();
        $searchCriteriaBuilder = $this->searchCriteriaBuilderFactory->create();
        $searchCriteriaBuilder->addFilters([$filterSku]);
        $searchCriteria = $searchCriteriaBuilder->create();
        $products = $this->productRepository->getList($searchCriteria)->getItems();
        foreach ($products as $product) {
            $productSku = $product->getSku();
            $productId = $this->product->getIdBySku($productSku);
            $product = $this->product->load($productId);
            $stockItem = $this->stockRegistry->getStockItemBySku($product->getSku());
            $stockItem->setQty($qty);
            $stockItem->save();
            $response["error"] = $this->_view->getLayout()
            ->createBlock('Vendor_Name\Module_Name\Block\Adminhtml\Ajax\Popup')
            ->setProduct($product)
            ->setQty($qty)
                ->setAttr($attr)
                ->toHtml();
            $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            $resultJson->setData($response);
            return $resultJson;
        }
    }

My js file

require(['jquery','jquery/ui'],function($){
$("#button-unique-identifier-here").click(function(e){
    // lấy dữ liệu
    var attr = $("input[name$='general[attr]']").val();
    var stocktaking = $("input[name$='general[stocktaking]']").val();
    var select = $("select[name$='general[formats]']").val();
    if (select == "sku" || select == "name"){
        try{
            // stocktaking là chữ hoặc nhỏ hơn 1
            if (isNaN(stocktaking) || stocktaking < 1) {
                alert("StockTaking Isn't Number, Please Try Again")
                return false;
            } else {
                if (attr && stocktaking) {
                    // chạy qua controller
                    url = window.validateUrl;
                    // ajax
                    jQuery.ajax({
                        url: url,
                        dataType: 'json',
                        type : 'post',
                        data: {attr: attr,qty: stocktaking,select:select},
                        showLoader: true,
                        success: function(data) {
                            if (data.popupValidate) {
                                //popup success
                                var popup = $('<div class="themecafe-free-popup"/>').html(data.popupValidate).modal({
                                    modalClass: 'changelog',
                                    buttons: [{

                                        text: 'Close',
                                        click: function () {
                                            this.closeModal();
                                        }
                                    },{
                                        text: 'Save',
                                        click: function () {
                                            this.closeModal();
                                            jQuery.ajax({
                                                class:'save',
                                                url: window.saveUrl,
                                                dataType: 'json',
                                                type : 'post',
                                                data: {attr: attr,qty: stocktaking,select:select},
                                                showLoader: true,
                                                success: function(data) {
                                                    console.log(data);

                                                    if (data.success) {
                                                        //popup success
                                                        var popup = $('<div class="themecafe-free-popup"/>').html(data.success).modal({
                                                            modalClass: 'changelog',
                                                            buttons: [{
                                                                text: 'Close',
                                                                click: function () {
                                                                    this.closeModal();
                                                                }
                                                            }]
                                                        });
                                                        popup.modal('openModal');
                                                        //end popup success
                                                        //popup error
                                                    } else if (data.error) {
                                                        var popup = $('<div class="themecafe-free-popup"/>').html(data.error).modal({
                                                            modalClass: 'changelog',
                                                            buttons: [{
                                                                text: 'Close',
                                                                click: function () {
                                                                    this.closeModal();
                                                                }
                                                            }]
                                                        });
                                                        popup.modal('openModal');
                                                        //end popup error
                                                    }

                                                }
                                            });
                                            return false;
                                        }
                                    }]
                                });
                                popup.modal('openModal');
                                //end popup success
                            }else if (data.error) {
                                var popup = $('<div class="themecafe-free-popup"/>').html(data.error).modal({
                                    modalClass: 'changelog',
                                    buttons: [{
                                        text: 'Close',
                                        click: function () {
                                            this.closeModal();
                                        }
                                    }]
                                });
                                popup.modal('openModal');
                                //end popup error
                            }
                        }
                    });
                }else{
                    // Nếu không có sku và stocktaking
                    if(!attr && !stocktaking){
                        alert("Please Enter SKU And STOCKTAKING")
                    }
                    // Nếu không có sku
                    else if(!attr){
                        alert("Please Enter SKU");
                    }
                    // Nếu không có stocktaking
                    else if(!stocktaking){
                        alert("Please Enter STOCKTAKING");
                    }
                }
            }
        }
        catch{
            alert("Please Try Again !!!");
        }
    }
})

});

My popupValidate.phtml open before saving data

enter image description here

Popup After save data

enter image description here

2 Answers 2

0

Try the following way:

Add the following code snippet on top:

use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\SearchCriteriaBuilderFactory;
use Magento\Framework\Api\FilterBuilder;

Then DI:

public function __construct(
    ProductRepository $productRepository,
    SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory,
    FilterBuilder $filterBuilder
) {
    $this->productRepository = $productRepository;
    $this->searchCriteriaBuilderFactory = $searchCriteriaBuilderFactory;
    $this->filterBuilder = $filterBuilder;
}

Now:

if ( value == sku) {
    $filter = $this->filterBuilder->setField('sku')->setValue('24-MB01')->create();
}

if (value == name ) {
    $filter = $this->filterBuilder->setField('name')->setValue('Strive Shoulder Pack')->create();
}
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->searchCriteriaBuilderFactory->create();
$searchCriteriaBuilder->addFilters([$filter]);
$searchCriteria = $searchCriteriaBuilder->create();
$products = $this->productRepository->getList($searchCriteria)->getItems();
foreach ($products as $product) {
    error_log($product->getId());
}

You can merge your modification inside products loop.

9
  • thanks Sohel Rana, but i want update by only sku or name, user enter text and qty, click save -> if value = name -> update by name, if value = sku -> update by sku, look my form
    – Brian NN
    Commented Feb 28, 2019 at 6:44
  • Check updated answer
    – Sohel Rana
    Commented Feb 28, 2019 at 7:02
  • thanks you, how to use ProductRepository SearchCriteriaBuilderFactory FilterBuilder
    – Brian NN
    Commented Feb 28, 2019 at 7:09
  • Check updated answer
    – Sohel Rana
    Commented Feb 28, 2019 at 7:12
  • When searching by name -> $product->getId() show. When searching by sku -> $product->getId() not show. Check updated question
    – Brian NN
    Commented Feb 28, 2019 at 7:44
0

You need to Just load product

$pro->setStockData(['qty' => Product_QTY, 'is_in_stock' => true]);
$pro->setQuantityAndStockStatus(['qty' => Product_QTY, 'is_in_stock' => true]);
$pro->save();

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.