Show category with images in homepage Magento2 - magento2

Show category with images in homepage Magento2
http://ibnab.com/en/blog/magento-2/magento-2-frontend-how-to-call-category-collection-on-home-page
This article working fine but I need to show category image.How to fetch category images also
I am using $category->getImageUrl();
but its not working

I was able to get this to show on the homepage by combining the tutorial and R T's answer. Because i didn't have a _objectManager (and the page was kicking an error when i tried R T's code) working on that page, I included the category model in the block file (Collection.php)
protected $_categoryHelper;
protected $categoryFlatConfig;
protected $topMenu;
protected $categoryView;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Helper\Category $categoryHelper,
\Magento\Catalog\Model\Indexer\Category\Flat\State $categoryFlatState,
\Magento\Theme\Block\Html\Topmenu $topMenu,
\Magento\Catalog\Model\Category $categoryView
) {
$this->_categoryHelper = $categoryHelper;
$this->categoryFlatConfig = $categoryFlatState;
$this->topMenu = $topMenu;
$this->categoryView = $categoryView;
parent::__construct($context);
}
I then added a method to call in the phtml at the bottom of the block file.
public function getCategoryView() {
return $this->categoryView;
}
In the phtml (storecategories.phtml) I changed up the code to work like this.
<?php
$categories = $this->getStoreCategories(true,false,true);
$categoryHelper = $this->getCategoryHelper();
?>
<ul>
<?php
foreach($categories as $category):
if (!$category->getIsActive()) {
continue;
}
?>
<li><a href="<?php echo $categoryHelper->getCategoryUrl($category) ?>">
<?php
$catId = $category->getId();
$categoryAgain = $this->getCategoryView()->load($catId);
$_outputhelper = $this->helper('Magento\Catalog\Helper\Output');
$_imgHtml = '';
if ($_imgUrl = $categoryAgain->getImageUrl()) {
$_imgHtml = '<img src="' . $_imgUrl . '" />';
$_imgHtml = $_outputhelper->categoryAttribute($categoryAgain, $_imgHtml, 'image');
/* #escapeNotVerified */
echo $_imgHtml;
}
?>
<?php echo $category->getName() ?></a></li>
<?php endforeach; ?>
</ul>
And then i added the new call into the di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Ibnab\CategoriesSide\Block\CategorisCollection">
<arguments>
<argument name="deleteorderAction" xsi:type="array">
<item name="context" xsi:type="string">\Magento\Framework\View\Element\Template\Context</item>
<item name="helper" xsi:type="string">\Magento\Catalog\Helper\Category</item>
<item name="flatstate" xsi:type="string">\Magento\Catalog\Model\Indexer\Category\Flat\State</item>
<item name="menu" xsi:type="string">\Magento\Theme\Block\Html\Topmenu</item>
<item name="categoryview" xsi:type="string">\Magento\Catalog\Model\Category</item>
</argument>
</arguments>
</type>

I've managed to do this as below in template:
$category = $this->_objectManager->create('Magento\Catalog\Model\Category')->load($item->getId());
$_outputhelper = $this->helper('Magento\Catalog\Helper\Output');
$_imgHtml = '';
if ($_imgUrl = $category->getImageUrl()) {
$_imgHtml = '<img src="' . $_imgUrl . '" />';
$_imgHtml = $_outputhelper->categoryAttribute($category, $_imgHtml, 'image');
/* #escapeNotVerified */
echo $_imgHtml;
}
hope it helps

Related

Magento 2.2 - Append Attribute Name To Product Name (H1)

This is driving me nuts, I created a module with a helper:
namespace MyNamespace\MyModule\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
protected $registry;
public function __construct
(
\Magento\Framework\Registry $registry,
\Magento\Eav\Api\AttributeSetRepositoryInterface $attributeSet
) {
$this->registry = $registry;
$this->attributeSet = $attributeSet;
}
public function getTitle()
{
$this->product = $this->registry->registry('product');
$product_name = $this->product->getName();
$attributeSetRepository = $this->attributeSet->get($this->product->getAttributeSetId());
if ($attributeSetRepository->getAttributeSetName() == "Default Engine Component"){
$engine = $this->product->getAttributeText('engine_select');
if (!is_array($engine)){
return "$engine $product_name";
}
}
return $product_name;
}
}
...and this works as it should. Then I added the following to:
/app/design/frontend/vendor/theme/Magento_Catalog/layout/catalog_product_view.xml
<referenceBlock name="page.main.title">
<action method="setPageTitle">
<argument name="title" xsi:type="helper" helper="MyNamespace\MyModule\Helper\Data::getTitle"></argument>
</action>
</referenceBlock>
...but it changes nothing on the product page. I know it's getting called as I can echo out the vars and they show at the top of the page, but it seems that the XML isn't doing what I hoped it would.
Anyone got any ideas?
So, tried multiple variations of achieving what I wanted but in the end, I created a template under Magento_Catalog/templates/product (in my theme), which was based of the magento-theme title.phtml and then modified the page.main.title block in the catalog_product_view layout file.
The template code may look a bit odd (getAttribute and then getAttributeText) but there's no error handling for getAttributeText and with getAttribute, if an attribute has multiple values, it's returned in a string, not an array like getAttributeText. It would have been nicer if I could have made sure the value was always present by checking which attribute set was being used but although getAttributeSetId is part of the product model, it's not available in the product/view interceptor and tbh, I've given up on trying to figure out how all that works!
Anyway, this has taken far more hours than I'd care to admit to figure out so here's the code, hope it helps someone!
Template:
<?php
$product = $block->getProduct();
$product_name = $product->getName();
$attr_exists = $product->getResource()->getAttribute('attr_code');
$title = $product_name;
$cssClass = $block->getCssClass() ? ' ' . $block->getCssClass() : '';
if ($attr_exists){
$attr_name = $product->getAttributeText('attr_code');
if (!is_array($attr_name)){
$title = "$attr_name $product_name";
}
}
?>
<?php if ($title): ?>
<div class="page-title-wrapper<?= /* #escapeNotVerified */ $cssClass ?>">
<h1 class="page-title"
<?php if ($block->getId()): ?> id="<?= /* #escapeNotVerified */ $block->getId() ?>" <?php endif; ?>
<?php if ($block->getAddBaseAttributeAria()): ?>
aria-labelledby="<?= /* #escapeNotVerified */ $block->getAddBaseAttributeAria() ?>"
<?php endif; ?>>
<?= /* #escapeNotVerified */ $title ?>
</h1>
<?= $block->getChildHtml() ?>
</div>
<?php endif; ?>
Layout:
<block name="page.main.title" class="Magento\Catalog\Block\Product\View" template="Magento_Catalog::product/product-h1.phtml" />

Get shopping cart details in Magento2

I know in Magento 1 you can get the shopping cart details on any page with:
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
$productId = $item->getProduct()->getId();
$productPrice = $item->getProduct()->getPrice();
}
How do I do the same thing in Magento 2?
protected $_checkoutSession;
public function __construct (
\Magento\Checkout\Model\Session $_checkoutSession
) {
$this->_checkoutSession = $_checkoutSession;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$cartData = $this->_checkoutSession->getQuote()->getAllVisibleItems();
$cartDataCount = count( $cartData );
}
you can get the quote data in observer
I figured this out by myself in the end:
<?php
$om = \Magento\Framework\App\ObjectManager::getInstance();
$cartData = $om->create('Magento\Checkout\Model\Cart')->getQuote()->getAllVisibleItems();
$cartDataCount = count( $cartData );
?>
<div class="bagDrop" id="bagDrop">
<h4>Quote Basket</h4>
<?php if( $cartDataCount > 1 ): ?>
<?php endif; ?>
<div class="bagDropWindow">
<?php if( $cartDataCount > 0 ): ?>
<div class="bagDropList" id="bagDropList">
<?php foreach( $cartData as $item ): ?>
<?php $product = $item->getProduct(); ?>
<?php $image = $product['small_image'] == '' ? '/pub/static/frontend/Clear/usb2u/en_GB/images/default-category-image_1.png' : '/pub/media/catalog/product' . $product['small_image']; ?>
<a href="<?php echo $product['request_path']; ?>" class="bagDropListItem">
<img src="<?php echo $image; ?>">
<p>
<span class="name"><?php echo $product['name']; ?></span><br>
<span class="qty">x <?php echo $item->getQty(); ?></span>
</p>
</a>
<?php endforeach; ?>
</div>
<?php else: ?>
<div class="emptyList">No products in your basket.</div>
<?php endif; ?>
</div>
<?php if( $cartDataCount > 1 ): ?>
<?php endif; ?>
</div>
Get Product Details in Checkout Page
<?php
namespace namespace\modulename\Block\xxx;
class xxx extends \Magento\Framework\View\Element\Template {
public function __construct(
\Magento\Checkout\Model\Cart $cart,
\namespace\modulename\Model\CrossSellFactory $crosssell,
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\ObjectManagerInterface $objectManager,
array $data = []
) {
parent::__construct($context, $data);
$this->cart = $cart;
$this->_crosssell = $crosssell;
$this->customerSession = $customerSession;
$this->_objectManager = $objectManager;
}
public function getProductIds()
{
$productInfo = $this->cart->getQuote()->getItemsCollection();
foreach ($productInfo as $item) {
$item[] = $item->getProductId();
echo"<pre>";print_r($item->getProductId());
}
return $item;
}
}
Put the above .php file in your block and return the value in phtml file like i shown below.
<?php
$Productdetails = $block->getProductIds();
echo"<pre>";print_r($Productdetails->getName());
?>
You can easily get the shopping cart details in the Magento 2 by implementing the below-mentioned code:
<?php
$object = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $object->create('Magento\Checkout\Model\Cart')->getQuote()->getAllVisibleItems();
$cartCount = count( $cart );
if($cartCount > 0){
echo $cartCount;
} else{
echo "0" ;
}
?>
Usage examples:
\Magento\Checkout\Block\Cart\AbstractCart::getQuote():
/**
* Get active quote
*
* #return Quote
*/
public function getQuote()
{
if (null === $this->_quote) {
$this->_quote = $this->_checkoutSession->getQuote();
}
return $this->_quote;
}
\Magento\Checkout\Block\Cart\Totals::getQuote():
/**
* Get active or custom quote
*
* #return \Magento\Quote\Model\Quote
*/
public function getQuote()
{
if ($this->getCustomQuote()) {
return $this->getCustomQuote();
}
if (null === $this->_quote) {
$this->_quote = $this->_checkoutSession->getQuote();
}
return $this->_quote;
}
\Magento\Checkout\Helper\Cart::getQuote():
/**
* Retrieve current quote instance
*
* #return \Magento\Quote\Model\Quote
* #codeCoverageIgnore
*/
public function getQuote()
{
return $this->_checkoutSession->getQuote();
}

Create Button in last page pagination codeigniter

Hello there I have problem
I wanna create button in my pagination codeIgniter just in last page for submit form
here my code:
Controller:
function index() {
/* pagination config */
$this->load->library('pagination');
$config['base_url'] = site_url('dcm/index');
$config['per_page'] = 6;
$config['num_link'] = 5;
$config['next_link'] = 'Next';
$config['prev_link'] = 'Prev' ;
$config['total_rows'] = $this->db->get('soal')->num_rows();
/* this my form still have problem but I have different post for this one */
/* if you have any Idea for this please check my Question */
$data['form_action'] = site_url('dcm/index');
$jawab = $this->input->post('jawab');
$id_soal = $this->input->post('id_soal');
$this->dcm_model->inputJawab();
/* */
/* pagination setting */
$this->pagination->initialize($config);
$data['query'] = $this->db->get('soal', $config['per_page'], $this->uri->segment(3));
$data['link'] = $this->pagination->create_links();
$this->load->view('dcm/soal', $data);
}
in view:
<form action="<?php echo $form_action; ?>">
<?php foreach($query->result() as $row) { ?>
<?php echo $row->id_soal . '. ' . $row->soal; ?>
<input type="checkbox" checked="checked" value="<?=$row->id_soal;?>" name="jawab[]" />
<?php } ?>
<?php echo $link; ?>
</form>
<input align="center" type="submit" value="selesai" />
You can check if you are on the last page with this code:
if($this->pagination->cur_page >=
ceil($this->pagination->total_rows / $this->pagination->per_page))
{
$isLastPage = true;
}
else
{
$isLastPage = false;
}
You can pass the $isLastPage variable to your view.

Type of Flash Messenger in Zend

Is it possible or How can i give a type to a FlashMessage in Zend?
For example
/* This is a "Success" message */
$this -> _helper -> FlashMessenger('You are successfully created a post.');
/* This is an "Error" message */
$this -> _helper -> FlashMessenger('There is an error while creating post.');
/* This is just a "Notification" message */
$this -> _helper -> FlashMessenger('Now you can see your Post');
I think the best way to do this is by using the flashmessenger namespaces:
/* success message */
$this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Post created!');
/* error message */
$this->_helper->FlashMessenger()->setNamespace('error')->addMessage('You have no permissions');
And then in your layout you can get the messages added to each namespace:
<?php $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
<?php if ($flashMessenger->setNamespace('success')->hasMessages()): ?>
<div class="message success">
<?php foreach ($flashMessenger->getMessages() as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($flashMessenger->setNamespace('error')->hasMessages()): ?>
<div class="message error">
<?php foreach ($flashMessenger->getMessages() as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
At one time you used assoc arrays to do this... Im not ure if this is still current or not...
/* This is a "Success" message */
$this -> _helper -> FlashMessenger(array('success' => 'You are successfully created a post.'));
/* This is an "Error" message */
$this -> _helper -> FlashMessenger(array('error' => 'There is an error while creating post.'));
/* This is just a "Notification" message */
$this -> _helper -> FlashMessenger(array('notice' => 'Now you can see your Post'));
It is possible. Sample implementation in described in this blog post:
Zend Framework: View Helper Priority Messenger | emanaton
Excerpt:
class AuthController extends Zend_Controller_Action {
function loginAction() {
. . .
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($this->view->form->isValid($formData)) {
. . .
} else {
$this->view->priorityMessenger('Login failed.', 'error');
}
. . .
}
}
Method signatures in Zend Framework 1.12.x for FlashMessenger:
public function addMessage($message, $namespace = null)
public function getMessages($namespace = null)
public function hasMessages($namespace = null)
public function clearMessages($namespace = null)
So to set messages the following will work:
/* success message */
$this->_helper->flashMessenger()->addMessage('Post created!', 'success');
/* error message */
$this->_helper->flashMessenger()->addMessage('You have no permissions', 'error');
And for the view, the following should work:
<?php $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
<?php if ($flashMessenger->hasMessages('success')): ?>
<div class="message success">
<?php foreach ($flashMessenger->getMessages('success') as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($flashMessenger->hasMessages('error')): ?>
<div class="message error">
<?php foreach ($flashMessenger->getMessages('error') as $msg): ?>
<?php echo $msg ?>
<?php endforeach; ?>
</div>
<?php endif; ?>

Creating child CMS pages in Magento

I would like to create a subordinate set of CMS pages in Magento so that the breadcrumb navigation at the top of the page looks like this:
Home > Parent CMS Page > Child CMS Page
Even though I can specify a hierarchical relationship with the URL key field, it seems to be that all CMS pages in Magento are listed in the root directory by default:
Home > Child CMS Page
Any ideas?
You are right, there is no hierarchy of CMS pages in Magento. The best solution would be to create a real hierarchy by adding a parent_id to CMS pages and modifying the CMS module to handle nested URLs and breadcrumbs. But that requires a lot of coding.
A quick-and-dirty hack is to modify the breadcrumbs manually on each subpage by adding something like this to the layout update XML:
<reference name="root">
<action method="unsetChild"><alias>breadcrumbs</alias></action>
<block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs">
<action method="addCrumb">
<crumbName>home</crumbName>
<crumbInfo><label>Home page</label><title>Home page</title><link>/</link></crumbInfo>
</action>
<action method="addCrumb">
<crumbName>myparentpage</crumbName>
<crumbInfo><label>My Parent Page</label><title>My Parent Page</title><link>/myparentpage/</link></crumbInfo>
</action>
<action method="addCrumb">
<crumbName>mysubpage</crumbName>
<crumbInfo><label>My Sub Page</label><title>My Sub Page</title></crumbInfo>
</action>
</block>
</reference>
I had the same problem with breadcrumbs and cms pages a few days ago check here ->
Similar to Anders Rasmussen post I edited every cms page manually
In breadcrumbs.phtml I added a little condition to define if a Page is a CMS page (thanks to Alan Storm) and remove standard crumb(s) and added new crumbs via xmllayout.
<?php
if($this->getRequest()->getModuleName() == 'cms'){
unset($crumbs['cms_page']);
}
?>
xml:
<reference name="breadcrumbs">
<action method="addCrumb">
<crumbName>cms_page_1st_child</crumbName>
<crumbInfo><label>1st child</label><title>1st child</title><link>/1st child/</link></crumbInfo>
</action>
<action method="addCrumb">
<crumbName>cms_page_2nd_child</crumbName>
<crumbInfo><label>2nd child</label><title>2nd child</title></crumbInfo>
</action>
</reference>
hope that helps,
Rito
For enterprise (version 1.12) use this code at following file, location is:
default->template->page->html->breadcrumb.phtml.
<?php
$cms_id = Mage::getSingleton('cms/page')->getPageId();
if($cms_id):
if($_SERVER['REQUEST_URI']) {
$trim_data = substr($_SERVER['REQUEST_URI'],1);
$data = explode('/',$trim_data);
}
$cms_collection = array();
$url_full = '';
$cms_enterprise = '';
foreach($data as $identifier) {
$page_data = Mage::getModel('cms/page')->getCollection()
->addFieldToFilter('identifier', $identifier);
if($page_data) {
foreach($page_data as $single) {
if($single->getContentHeading() != null) {
if($single->getPageId()) {
$cms_enterprise = Mage::getModel('enterprise_cms/hierarchy_node')->getCollection()
->addFieldToFilter('page_id', $single->getPageId());
foreach($cms_enterprise as $single_enterprise) {
$url_full = $single_enterprise->getRequestUrl();
}
}
$cms_collection[] = array($single->getTitle(), $single->getContentHeading(), $url_full );
} else {
if($single->getPageId()) {
$cms_enterprise = Mage::getModel('enterprise_cms/hierarchy_node')->getCollection()
->addFieldToFilter('page_id', $single->getPageId());
foreach($cms_enterprise as $single_enterprise) {
$url_full = $single_enterprise->getRequestUrl();
}
}
$cms_collection[] = array($single->getTitle(), $single->getTitle(), $url_full );
}
}
}
}
$count = count($cms_collection);
$i = 1;
?>
<?php if(count($cms_collection)): ?>
<div class="breadcrumbs">
<ul>
<li>
<a href="<?php echo $this->getUrl() /*Home*/ ?>" title="<?php echo $this->__('Home'); /*Home Title*/ ?>">
<?php echo $this->__('Home'); /*Home Name*/ ?>
</a>
<span>> </span>
</li>
<?php foreach($cms_collection as $key=>$value): ?>
<?php if($i == $count): ?>
<li>
<strong>
<?php echo $value[1]; /*Name*/ ?>
</strong>
</li>
<?php else: ?>
<li>
<a href="<?php echo $this->getUrl().$value[2] /*Identifier*/ ?>" title="<?php echo $value[0] /*Title*/ ?>">
<?php echo $value[1]; /*Name*/ ?>
</a>
<span>> </span>
</li>
<?php endif; ?>
<?php $i++; ?>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php else: ?>
<?php if($crumbs && is_array($crumbs)): ?>
<div class="breadcrumbs">
<ul>
<?php foreach($crumbs as $_crumbName=>$_crumbInfo): ?>
<li class="<?php echo $_crumbName ?>">
<?php if($_crumbInfo['link']): ?>
<?php echo $this->htmlEscape($_crumbInfo['label']) ?>
<?php elseif($_crumbInfo['last']): ?>
<strong><?php echo $this->htmlEscape($_crumbInfo['label']) ?></strong>
<?php else: ?>
<?php echo $this->htmlEscape($_crumbInfo['label']) ?>
<?php endif; ?>
<?php if(!$_crumbInfo['last']): ?>
<span>> </span>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
Thanks,
Kashif
This is my solution of the problem. I use custom layout for most of the CMS pages (default/template/page/cmsLayout.phtml) so I heve added following code into the layout file:
<div class="col-main">
<?php
$urlPart=str_replace(Mage::getUrl(),'',Mage::getUrl('', array('_current' => true,'_use_rewrite' => true)));
$urlPart=explode('/',$urlPart);
$string='';
$return='<div class="breadcrumbs"><ul><li class="home">Home<span> / </span></li>';
$count=count($urlPart);
foreach($urlPart as $value)
{
$count--;
$string.='/'.$value;
$string=trim($string, '/');
$pageTitle = Mage::getModel('cms/page')->load($string, 'identifier')->getTitle();
if($count==0)
$return.='<li><strong>'.$pageTitle.'</strong></li>';
else
$return.='<li>'.$pageTitle.'<span> / </span></li>';
}
echo $return.'</li></ul></div>';
?>
<?php echo $this->getChildHtml('global_messages') ?>
<?php echo $this->getChildHtml('content') ?>
</div>
update
-oops- this might be an enterprise feature only
There is a built-in CMS page hierarchy option in Magento.
To turn it on:
System > Configuration > General > Content Management > CMS Page Hierarchy - see here
To organise the hierarchy tree:
CMS > Pages > Manage Hierarchy
To manage the position of a page in the tree, after saving a page, go to its "hierarchy tab" - see the screenshot:
In the example the page "Our culture" is a child of "jobs" and not of the root directory
For Magento Enterprise, I have created an extension to solve this. It uses the built in CMS Hierarchy in the backend. The module is called Demac/BananaBread and shouldn't require any hacks or customization.
Direct download: here
Link to article: http://www.demacmedia.com/magento-commerce/introducing-demac_bananabread-adding-cms-breadcrumbs-from-the-hierarchy-in-magento/
I built a custom block as to generate the crumbs (removing the built-in and replacing with the custom one below in the layout):
namespace Uprated\Theme\Block\Html;
class UpratedBreadcrumbs extends \Magento\Framework\View\Element\Template
{
/**
* Current template name
*
* #var string
*/
public $crumbs;
protected $_template = 'html/breadcrumbs.phtml';
protected $_urlInterface;
protected $_objectManager;
protected $_repo;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\UrlInterface $urlInterface,
\Magento\Framework\ObjectManagerInterface $objectManager,
array $data = [])
{
$this->_urlInterface = $urlInterface;
$this->_objectManager = $objectManager;
$this->_repo = $this->_objectManager->get('Magento\Cms\Model\PageRepository');
$this->getCrumbs();
parent::__construct($context, $data);
}
public function getCrumbs() {
$baseUrl = $this->_urlInterface->getBaseUrl();
$fullUrl = $this->_urlInterface->getCurrentUrl();
$urlPart = explode('/', str_replace($baseUrl, '', trim($fullUrl, '/')));
//Add in the homepage
$this->crumbs = [
'home' => [
'link' => $baseUrl,
'title' => 'Go to Home Page',
'label' => 'Home',
'last' => ($baseUrl == $fullUrl)
]
];
$path = '';
$numParts = count($urlPart);
$partNum = 1;
foreach($urlPart as $value)
{
//Set the relative path
$path = ($path) ? $path . '/' . $value : $value;
//Get the page
$page = $this->getPageByIdentifier($path);
if($page) {
$this->crumbs[$value] = [
'link' => ($partNum == $numParts) ? false : $baseUrl . $path,
'title' => $page['title'],
'label' => $page['title'],
'last' => ($partNum == $numParts)
];
}
$partNum++;
}
}
protected function getPageByIdentifier($identifier) {
//create the filter
$filter = $this->_objectManager->create('Magento\Framework\Api\Filter');
$filter->setData('field','identifier');
$filter->setData('condition_type','eq');
$filter->setData('value',$identifier);
//add the filter(s) to a group
$filter_group = $this->_objectManager->create('Magento\Framework\Api\Search\FilterGroup');
$filter_group->setData('filters', [$filter]);
//add the group(s) to the search criteria object
$search_criteria = $this->_objectManager->create('Magento\Framework\Api\SearchCriteriaInterface');
$search_criteria->setFilterGroups([$filter_group]);
$pages = $this->_repo->getList($search_criteria);
$pages = ($pages) ? $pages->getItems() : false;
return ($pages && is_array($pages)) ? $pages[0] : [];
}
Then used a slightly modified .phtml template to display them:
<?php if ($block->crumbs && is_array($block->crumbs)) : ?>
<div class="breadcrumbs">
<ul class="items">
<?php foreach ($block->crumbs as $crumbName => $crumbInfo) : ?>
<li class="item <?php /* #escapeNotVerified */ echo $crumbName ?>">
<?php if ($crumbInfo['link']) : ?>
<a href="<?php /* #escapeNotVerified */ echo $crumbInfo['link'] ?>" title="<?php echo $block->escapeHtml($crumbInfo['title']) ?>">
<?php echo $block->escapeHtml($crumbInfo['label']) ?>
</a>
<?php elseif ($crumbInfo['last']) : ?>
<strong><?php echo $block->escapeHtml($crumbInfo['label']) ?></strong>
<?php else: ?>
<?php echo $block->escapeHtml($crumbInfo['label']) ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
Working fine for me in 2.1