Magento 2 Custom Module – Include Custom Module Block in PHTML File

blocksclassmagento2modulephtml

I've created a custom module for a distributor search with a php class/block inside.

Module Structure:

- /Distributor Search
    - /Block
         - DistributorSearch.php
    - /etc
        - module.xml
    - /view
         - /frontend
              - /template
                  - distributor-search.phtml
    - registration.php

I've tried to reference the DistributorSearch block when adding my phtml to the page in my default.xml in my theme.

<block class="Autosmart\DistributorSearch\Block\DistributorSearch" name="distributor.search" template="Autosmart_DistributorSearch::distributor-search.phtml"></block>

I've also tried to keep the phtml file within my theme and include like:

 <block class="Autosmart\DistributorSearch\Block\DistributorSearch" name="distributor.search" template="Magento_Theme::html/distributor-search.phtml"></block>

However I keep getting 500 errors and struggling to get the phtml to show on the page using our module class/block.

I can get the phtml to show on the page by but then I cannot use our methods inside my class DistributorSearch.php?

<block class="Magento\Framework\View\Element\Template" name="distributor.search" template="Autosmart_DistributorSearch::distributor-search.phtml"></block>

Any help to get this working would be appreciated.

UPDATE:

Block class content:

<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Autosmart\DistributorSearch\Block;

/**
 * Local Distributor Search Header Block
 */
class DistributorSearch extends \Magento\Framework\App\Config\ScopeConfigInterface
{
    /**
     * Retrieve store name
     *
     * @return string
     */
    public function getStoreName()
    {
        return "testx";
    }
}

distributor-search.phtml contents:

<?php 
echo $block->getStoreName();
?>
Test Content 

Best Answer

My best guess is that your block is extending \Magento\Framework\App\Config\ScopeConfigInterface instead of \Magento\Framework\View\Element\Template.

A block should always be a child of \Magento\Framework\View\Element\AbstractBlock, since it contains certain logic to render the HTML and handle layout updates.

I think you're getting the 500 error because your block class is not a Block.