Magento 2 - How Can I Send Success and Error in JSON and from Frontend update product price and enable/'disable?

magento.stackexchange https://magento.stackexchange.com/questions/317027

Pregunta

Ajax runs on page load i want to run it on button click.

I create one Module and make a custom tab which is display some product with name and price and if the product is enable/disable. I want that user update that price from front-end and enable and disable that product from front-end.[![enter image description here][1]][1]

This is my Controller File

<?php
namespace Deal\Val\Controller\Valuation;

use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\ResourceModel\Product\Action;

class Index extends \Magento\Framework\App\Action\Action
{
protected $customerSession;
protected $urlInterface;
protected $customer;
private $productAction;

public function __construct(
    Action $productAction,
    \Magento\Customer\Model\Session $customerSession,
    \Magento\Framework\UrlInterface $urlInterface,
    \Dealers\Validation\Model\Customer $customer,
    \Magento\Framework\App\Action\Context $context
) {
    $this->urlInterface = $urlInterface;
    $this->customerSession = $customerSession;
    $this->customer = $customer;
    $this->productAction = $productAction;
    parent::__construct($context);
}


public function execute()
{
    if(!$this->customerSession->isLoggedIn()) {
        $this->messageManager->addErrorMessage("You must be logged in to view product");
        $this->customerSession->setAfterAuthUrl($this->urlInterface->getCurrentUrl());
        $this->customerSession->authenticate();
        return;
    }
    /*$data = $this->getRequest()->getPost();
    $this->customer->saveproduct($data);*/
    $productIds = [47];

    $storeId = 0;

    $attributes = [
        //'status' => Status::STATUS_ENABLED,
        'price' => 70
    ];

    $this->productAction->updateAttributes($productIds, $attributes, $storeId);
    $this->_view->loadLayout(); 
    $this->_view->renderLayout(); 
}
}

This is my Model File

<?php
namespace Deal\Val\Model;

use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\ResourceModel\Product\Action;

 class Customer
{
/**
 * @var Action
 */
private $productAction;

public function __construct(
    Action $productAction
) {
    $this->productAction = $productAction;
}

public function execute()
{
    /** Array of product ids */
    $productIds = [47];

    /** Contains the id of the store in which you would like to enable/disable the product */
    $storeId = 0;

    /**
     * You can put any number of product attributes here. However, in the scope of this code we are going to
     * only enable/disable the product.
     */
    $attributes = [
        'status' => Status::STATUS_ENABLED
    ];

    $this->productAction->updateAttributes($productIds, $attributes, $storeId);
}
}

This is my JS file

require(["jquery"],function($) {
$(document).ready(function() {

    $( "#price" ).click(function() {
        let customurl = "<?php echo $this->getUrl().'customer/valuation/index'?>";
        let dataid = $(this).data('id');
        $.ajax({
            url: customurl,
            type: 'POST',
            dataType: 'json',
            data: {
                dataid: dataid
            },
            complete: function(response) {             
                console.log(response); 
            },
        });
    });

});
console.log('aa');
});

How can i send response success or error in JSON format.

¿Fue útil?

Solución

Check this article Update Price

Otros consejos

In your model file, you first need to load the product, then update it's price and save it.

I am updating your model code:

<?php
namespace Deal\Val\Model;

use Magento\Catalog\Model\Product\Attribute\Source\Status;

 class Customer
{
    protected $productRepository;

    public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ) {
        $this->productRepository = $productRepository;
    }

    public function execute()
    {
        /** Array of product ids */
        $productIds = [47];
        foreach($productIds as $id){
            $product = $this->productRepository->getById($id);
            $product->setPrice(100); //Update anything here
            $product->save();
        }
    }
}

Hope this will help you resolve your issue.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top