I'm creating my first module which has been going well, I've managed to create the controller, block and route and can access the page.
I'm now trying to perform an ajax query and return some product data but this is where I'm now struggiling, I've got the following files:
<?php
namespace MoudleName\ProductSelector\Controller\Ajax;
use \Magento\Backend\Block\Template\Context;
use \Magento\Framework\Controller\Result\JsonFactory;
use \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
class Index extends \Magento\Framework\App\Action\Action
{
protected $resultJsonFactory;
protected $_productCollectionFactory;
public function __construct($context, $resultJsonFactory, $productCollectionFactory) {
$this->resultJsonFactory = $resultJsonFactory;
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context);
}
public function execute()
{
$result = $this->resultJsonFactory->create();
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3); // fetching only 3 products
if ($this->getRequest()->isAjax())
{
return $result->setData($collection);
}
}
}
This is the Ajax query:
$('.ajax-query').on('click', function (event) {
event.preventDefault();
$.ajax({
url: "/productselector/ajax/index",
cache: false,
dataType: "json",
success: function(data){
console.log(data);
}
});
});
But I just get a 500 error and in the logs I'm getting the following error:
3382#3382: *5889 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function ModuleName\ProductSelector\Controller\Ajax\Index::__construct(), 2 passed in /var/www/generated/code/ModuleName/ProductSelector/Controller/Ajax/index/Interceptor.php on line 14 and exactly 3 expected in /var/www/app/code/ModuleName/ProductSelector/Controller/Ajax/index.php:14
If anyone can shed any light on this it'd be great.
Thanks