1

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.

2
  • You want to disable from the frontend right ?
    – Tanmay
    Commented Jul 8, 2020 at 8:34
  • Yes and update price too, thanks for the reply @Tanmay
    – Prits
    Commented Jul 8, 2020 at 8:36

1 Answer 1

1

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.

14
  • It gives me this error " type Error occurred when creating object: " @Shoaib
    – Prits
    Commented Jul 10, 2020 at 15:49
  • Can you show full error message? Commented Jul 10, 2020 at 17:39
  • Updated the screenshot of error @Shoaib
    – Prits
    Commented Jul 10, 2020 at 18:03
  • instead of calling model file, you can move update product code in your controller. I have also created this type of module where user can update their products, I did the same, updated product in controller file Commented Jul 11, 2020 at 9:05
  • On moving that in Controller file still got the same error " Type Error occurred when creating object " @Shoaib
    – Prits
    Commented Jul 11, 2020 at 10:15

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.