Magento 2 – How to Call a Block from a Controller

controllersmagento2

I'm trying to adapt a module from prestashop to Magento. In this module my page is calling a script js with angular.js then the script himself have some function to interact from the controller who's getting a function from a class.

so i have in my phtml (the code is still for Prestashop for the moment):

<tr ng-repeat="(keyDescReplace,descReplace) in descReplaces">
                <td>{{ descReplace.toreplace }}</td>  //this is the calling of angular js
                <td>{{ descReplace.replaceby }}</td>  //this is the calling of angular js
</tr>

then in my js script i have

$scope.getDescReplaces();

in my controller i have

public function ajaxProcessGetDescReplaces()
    {
        die(Tools::jsonEncode(array(
            'descReplaces' => getAll()
        )));
    }

and finally in my class i have

public function getAll(){
    $data = array();
    $model = $this->contactFactory->create();
    $newData = $model->getCollection();
    foreach ($newData as $d )  {
        echo $d->getToreplace();
        echo $d->getReplaceby();

    // the base code was   return Db::getInstance()->executeS('SELECT * FROM `my table');
    }

i know it's not very clear but can someone help me pls to adapt the code to link the controller to the block so he can get the getAll() function.

Best Answer

You can call Block function inside controller using below way,

$getBlock = $this->getLayout()->createBlock("Mymodule\Adminpange\Block\Customblock");
$getBlock->getAll();

Where Mymodule\Adminpange\Block\Customblock pass your block class path.