Magento2 Blocks and Controllers – How to Call a Block Function in My Controller

blockscontrollersmagento2

I have a little problem to call a function from my block to my controller. I need to get a function from my block locate in Mymodule/AdminPage/Block/Adminhtml/Contactslist.php help pls i did it before once but I fail in every attempt i make.

<?php
  namespace Mymodule\AdminPage\Controller\Adminhtml\AdminDescsdev;

  class Index extends \Magento\Backend\App\Action
  {
    protected $resultPageFactory;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
         parent::__construct($context);
         $this->resultPageFactory = $resultPageFactory;
    }


    public function ajaxProcessGetDescReplaces()
    {
        die(jsonEncode(array(
            'descReplaces' => " function to call getAll() "
        )));
    }

    public function execute()
    {   
        return  $resultPage = $this->resultPageFactory->create();
    }
  }

here is my block :

<?php
namespace Mymodule\AdminPage\Block\Adminhtml;

use Magento\Backend\Block\Template;

class Contactslist extends \Magento\Backend\Block\Template
{

 public function __construct(
     \Magento\Backend\Block\Template\Context $context,
     \Mymodule\AdminPage\Model\ContactFactory $contactFactory,
     \Magento\Framework\View\Result\PageFactory $resultPageFactory,
     array $data = []
 ) {
      parent::__construct($context, $data);
      $this->contactFactory = $contactFactory;
      $this->resultPageFactory = $resultPageFactory;
 }

    public function getAll(){
    $data = array();
    $model = $this->contactFactory->create();
    $newData = $model->getCollection();
    $tabl = array();
    foreach ($newdata as $d )  {
        $tabl[] = array(
            'toreplace' => $d->getToreplace(),
            'replaceby' => $d->getReplaceby()
        );
    }
    return $tabl;
}
}

Best Answer

Just create instance through object manager and call your function

public function ajaxProcessGetDescReplaces()
{
    $blockInstance = $this->_objectManager->get('Mymodule\AdminPage\Block\Adminhtml\Contactslist');
    $blockInstance->getAll()
}