Pergunta

I have a block that returns a category by its ID. I loop on the category's children and I would like to be able to display their respective images and names.
for the moment I can display their names but not images urls.

here is my block

<?php

namespace Foo\Bar\Block;

use Magento\Backend\Block\Template\Context;
use Magento\Catalog\Api\CategoryRepositoryInterface;

class Orders extends \Magento\Framework\View\Element\Template
{ 
    protected $_categoryHelper;

    protected $categoryFlatConfig;

    protected $topMenu;

    /**
     * @var CategoryRepositoryInterface
     */
    private $categoryRepository;

    /**
     * Orders constructor.
     * @param Context                     $context
     * @param CategoryRepositoryInterface $categoryRepository
     */
    public function __construct(Context $context, CategoryRepositoryInterface $categoryRepository)
    {
        $this->categoryRepository = $categoryRepository;
        parent::__construct($context);
    }

    public function getCategoryById($id)
    {
        return $this->categoryRepository->get($id);
    }
}

here is my phtml

<?php

use Magento\Catalog\Model\Category\Interceptor;

/** @var Interceptor $category */
$category = $this->getCategoryById(63);

?>
<h1>
    <?php echo $category->getName(); ?>
</h1>
<p>
    url : <?php echo $category->getImageUrl(); ?> // OK
</p>
<?php

if ($category->hasChildren()) {
    $subCategories = $category->getChildrenCategories();
    echo '<ul>';
    foreach ($subCategories as $subCategory) {
        echo '<li>' . $subCategory->getName() . '</li>';
        echo '<li>' . $subCategory->getImageUrl() . '</li>'; // NOTHING HERE
    }
    echo '</ul>';
}
?>

I don't understand why my parent category can display the url of the image but not the children....

Foi útil?

Solução

Below is your modified .phtml code which will work. you can also use same function which you used in block. the main thing is you need to load category by id to get image URL.

<?php

use Magento\Catalog\Model\Category\Interceptor;

/** @var Interceptor $category */
$category = $this->getCategoryById(63);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
?>
<h1>
  <?php echo $category->getName(); ?>
</h1>
<p>
  url : <?php echo $category->getImageUrl(); ?> // OK
</p>
<?php

if ($category->hasChildren()) {
$subCategories = $category->getChildrenCategories();
echo '<ul>';
foreach ($subCategories as $subCategory) {

    $_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subCategory->getId());

    echo '<li>' . $subCategory->getName() . '</li>';
    echo '<li>' . $_category->getImageUrl() . '</li>'; // NOTHING HERE
}
echo '</ul>';
}
?>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top