This is my code:
app/code/Vendor/Module/view/frontend/templates/storecategories.phtml
<div>
<h3>
<a href="">
<?php
$categoryId = 65;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $_objectManager->create('Magento\Catalog\Model\Category')
->load($categoryId);
$childrenCategories = $category->getChildrenCategories();
echo $category->getName();
?>
</a>
</h3>
<ul>
<?php foreach($childrenCategories as $childrenCategory) {
echo "<li>" . "<a href=" . $childrenCategory->getUrl() . ">" . $childrenCategory->getName() . "</a>" . "</li>";}
?>
</ul>
For now it echo out categories and children categories.
What I want to achieve is to type block code
{{block class="Vendor\Module\Block\BlockName" category_id="49" template="Vendor_Module::storecategories.phtml"}}
into admin panel/Content/Pages/Home page/Content text area and call for categories and subcategories without using echo.
I suppose that I need to create Block file, but have no clue what code in it should look like.
Maybe I need controller as well and some changes in storecategories.phtml too?
1 Answer 1
You not need to create any controller but you have to create block class.
So,you have to create a module should have this command files:
app/code/{Vendor}/{Module}/composer.json
app/code/{Vendor}/{Module}/registration.php
app/code/{Vendor}/{Module}/etc/module.xml
then create a block file app/code/{Vendor}/{Module}/Block/BlockName and write a function and return children category from this function to phtml.
Block Class
<?php
namespace {Vendor}\{Module}\Block
use Magento\Framework\View\Element\Template;
class BlockName extends \Magento\Framework\View\Element\Template implements
\Magento\Framework\DataObject\IdentityInterface
{
/**
* @var \Magento\Catalog\Model\CategoryFactory
*/
private $categoryFactory;
public function __construct(
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
Template\Context $context,
array $data = [])
{
parent::__construct($context, $data);
$this->categoryFactory = $categoryFactory;
}
const CATEGORYID = 65;
public function getSubCatgories()
{
$category = $this->categoryFactory->create();
$category->load(self::CATEGORYID);
return $category;
}
/**
* Return unique ID(s) for each object in system
*
* @return string[]
*/
public function getIdentities()
{
return [\Magento\Catalog\Model\Category::CACHE_TAG, \Magento\Store\Model\Group::CACHE_TAG];
}
}
and phtml Code is
<div>
<h3>
<a href="">
<?php
$category =$this->getSubCatgories();
if(category){
$childrenCategories = $category->getChildrenCategories();
echo $category->getName();
?>
</a>
</h3>
<ul>
<?php foreach($childrenCategories as $childrenCategory) {
echo "<li>" . "<a href=" . $childrenCategory->getUrl() . ">" . $childrenCategory->getName() . "</a>" . "</li>";}
?>
</ul>
<?php }?>
</div>