0

I am making an ajax request in my module to grab some custom CRUD data to populate a select box on the fly.

I have a working ajax request and controller

Javascript

define(["jquery"], function($){
   return function(config, element) {

    $.ajax({
        url: 'leadmodel/ajax/index',
        type: 'POST',
        dataType: 'json',
        data: {},
        complete: function(response) {             
            console.log(response.responseJSON);
        },
        error: function (xhr, status, errorThrown) {
            console.log(xhr);
            console.log(status);
            console.log(errorThrown);
        }
      }); // ajax function end here

}

})

Vendor/Module/Controller/Ajax/Index.php

<?php 

namespace Vendorname\Modelname\Controller\Ajax; 

use Magento\Framework\Controller\ResultFactory; 
use Magento\Framework\App\Action\Action; 
use Magento\Framework\App\Action\Context; 

class Index extends Action { 

    protected $request; 

    public function __construct(
        Context $context,
        array $data = []
    ){ 
        parent::__construct($context, $data); 
    } 

    public function execute() { 

        $data = ['joe', 'bloggs'];

        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($data); 
        return $resultJson; 
    } 
}

Which works fine, it console log's the array and everything is great. But as soon as I pass a factory into the controller to build an array with custom CRUD model data, it breaks the controller and I just get a 500 error.

<?php 

namespace Vendorname\Modelname\Controller\Ajax; 

use Magento\Framework\Controller\ResultFactory; 
use Magento\Framework\App\Action\Action; 
use Magento\Framework\App\Action\Context; 
use Vendorname\Modelname\Api\Data\LeadModelInterface;

class Index extends Action { 

    protected $request; 
    protected $_leadmodelCollectionFactory;

    public function __construct(
        Context $context,
        \Vendorname\Modelname\Model\ResourceModel\LeadModel\CollectionFactory $leadmodelCollectionFactory,
        array $data = []
    ){ 
        $this->_leadmodelCollectionFactory = $leadmodelCollectionFactory;
        parent::__construct($context, $data); 
    } 

    public function execute() { 

        //Get the lead models
        $leadmodels = $this->_leadmodelCollectionFactory->create();

        //Start a new array
        $array = [];

        //Loop the lead models
        foreach($leadmodels->getLeadModels() as $leadmodel){
            $model = [];
            $model['name'] = $leadmodel->getLeadModelName();
            $model['id'] = $leadmodel->getId();
            array_push($array, $model);
        }

        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($array); 
        return $resultJson; 
    } 
}

Am I doing this wrong? How am I supposed to get CRUD data from a model in the controller to pass back to my ajax request?

0

change controller code with below code

<?php

namespace Vendorname\Modelname\Controller\Ajax;

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Vendorname\Modelname\Api\Data\LeadModelInterface;
use Magento\Framework\Controller\Result\JsonFactory;

class Index extends Action
{

    protected $request;
    protected $_leadmodelCollectionFactory;
    private $jsonFactory;

    public function __construct(
        Context $context,
        \Vendorname\Modelname\Model\ResourceModel\LeadModel\CollectionFactory $leadmodelCollectionFactory,
        JsonFactory $jsonFactory,
        array $data = []
    )
    {
        $this->_leadmodelCollectionFactory = $leadmodelCollectionFactory;
        $this->jsonFactory = $jsonFactory;
        parent::__construct($context, $data);
    }

    public function execute()
    {

        //Get the lead models
        $leadmodels = $this->_leadmodelCollectionFactory->create();

        //Start a new array
        $array = [];

        //Loop the lead models
        foreach ($leadmodels as $leadmodel) {
            $model = [];
            $model['name'] = $leadmodel->getLeadModelName();
            $model['id'] = $leadmodel->getId();
            array_push($array, $model);
        }

        $result = $this->jsonFactory->create();
        $result->setData($array);
        return $result;
    }
}
  • Still just getting Internal Server Error - Exception #0 (Magento\Framework\Exception\RuntimeException): Type Error occurred when creating object: Vendorname\Modelname\Controller\Ajax\Index\Interceptor – S_R Sep 13 at 10:39
  • this is error is just because we chage the constructure argument, please remove that class from generator folder, and clear cache – Jigs Parmar Sep 13 at 11:14
  • Still doesn't seem to be working? Am I definitely using the correct method to access model data in a controller? – S_R Sep 13 at 11:26
  • check my updated answer – Jigs Parmar Sep 13 at 11:34
  • I have changed my code and its working now, will upload my answer – S_R Sep 13 at 11:39
0

I'm not 100% sure what I was doing wrong, but I think it might have been the way I was trying to get the collection. I was trying to use a method called getLeadModels() which existed on the block.

I have changed my code to use the Lead Model Factory and the getCollection method and it seems to be working now.

<?php

namespace VendorName\ModelName\Controller\Ajax;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory; 

class Index extends Action {

    protected $request;
    protected $_leadmodelFactory;

    public function __construct(
        Context $context,
        \VendorName\ModelName\Model\LeadModelFactory $leadmodelFactory
    )
    {
        parent::__construct($context);
        $this->_leadmodelFactory = $leadmodelFactory;
    }

    public function execute(){

        //Get the lead models
        $leadmodels = $this->_leadmodelFactory->create();

        //Start a new empty array
        $array = [];

        foreach($leadmodels->getCollection() as $leadmodel){
            $model = [];
            $model['id'] = $leadmodel->getId();
            $model['name'] = $leadmodel->getLeadModelName();
            array_push($array, $model);
        }

        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($array); 
        return $resultJson; 
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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