Magento2: How to build a custom category link widget with attributes?main.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Why Getting categories and names on product view page Magento 2 fails?Error with Dependency Injection in widgetMagento 2 Add new field to Magento_User admin formAccount Link label generated by helper returns escaped htmlMagento offline custom Payment method with drop down listHow to solve Front controller reached 100 router match iterations in magento2Magento 2.3 Can't view module's front end page output?Magento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?

Counterexample: a pair of linearly ordered sets that are isomorphic to subsets of the other, but not isomorphic between them

How to replace the "space symbol" (squat-u) in listings?

If Earth is tilted, why is Polaris always above the same spot?

Python "triplet" dictionary?

In gnome-terminal only 2 out of 3 zoom keys work

Does a creature that is immune to a condition still make a saving throw?

Has any spacecraft ever had the ability to directly communicate with civilian air traffic control?

Confused by notation of atomic number Z and mass number A on periodic table of elements

Why do Ichisongas hate elephants and hippos?

What word means to make something obsolete?

Subtleties of choosing the sequence of tenses in Russian

What's the metal clinking sound at the end of credits in Avengers: Endgame?

How to back up a running remote server?

Binary Numbers Magic Trick

Past Perfect Tense

Does jamais mean always or never in this context?

Pawn Sacrifice Justification

Stark VS Thanos

Can someone publish a story that happened to you?

Where did the extra Pym particles come from in Endgame?

Were there two appearances of Stan Lee?

Why is current rating for multicore cable lower than single core with the same cross section?

Confusion about capacitors

How can I get precisely a certain cubic cm by changing the following factors?



Magento2: How to build a custom category link widget with attributes?


main.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Why Getting categories and names on product view page Magento 2 fails?Error with Dependency Injection in widgetMagento 2 Add new field to Magento_User admin formAccount Link label generated by helper returns escaped htmlMagento offline custom Payment method with drop down listHow to solve Front controller reached 100 router match iterations in magento2Magento 2.3 Can't view module's front end page output?Magento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm trying to build a category link widget similar to the core one, but that can pull in additional information from the category selected, such as the image thumbnail and maybe some custom category attributes we've created. I have created a module that constructs the widget, based on code from the core "Catalog Category Link" widget. That is working well in the Admin side (all widget options are the same as the standard one) and works for creation of a widget that appears on the page, the link works too on the front end. The module is set up with module.xml, registration.php in the usual places.



codeVendorCategoryWidgetetcwidget.xml



<?xml version="1.0" encoding="UTF-8"?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
<widget id="tec_catlink" class="VendorCategoryWidgetBlockWidgetLink" placeholder_image="Magento_Catalog::images/category_widget_link.png">
<label translate="true">Custom Category Link Widget</label>
<description>Link to specified category to fit with grid</description>
<parameters>
<parameter name="id_path" xsi:type="block" visible="true" required="true" sort_order="10">
<label translate="true">Category</label>
<block class="MagentoCatalogBlockAdminhtmlCategoryWidgetChooser">
<data>
<item name="button" xsi:type="array">
<item name="open" xsi:type="string" translate="true">Select Category...</item>
</item>
</data>
</block>
</parameter>
<parameter name="anchor_text" xsi:type="text" visible="true">
<label translate="true">Anchor Custom Text</label>
<description translate="true">If empty, we'll use the category name here.</description>
</parameter>
<parameter name="title" xsi:type="text" visible="true">
<label translate="true">Anchor Custom Title</label>
</parameter>
<parameter name="template" xsi:type="select" visible="true">
<label translate="true">Template</label>
<options>
<option name="default"
value="widget/category_link.phtml"
selected="true">
<label translate="true">Grid Link Template</label>
</option>
</options>
</parameter>
</parameters>
<containers>
<container name="content.subcats">
<template name="grid" value="default" />
<template name="list" value="list" />
</container>
</containers>
</widget>
</widgets>


On the front end the link appears correctly but somehow the function that retrieves the label is broken and only appears if Anchor Text has been entered (looks like $entityresource is empty). In addition I want to be able to call attributes from the category for use on the front end but it seems like I don't have the right dependencies in there or I'm not creating/calling a category object correctly that the core methods will work on (rather than recreating functions).



codeVendorCategoryWidgetviewfrontendtemplateswidgetcategory_link.phtml



<?php
// @codingStandardsIgnoreFile
?>

<li class="subcat-item widget block-category-link">
<a <?= /* @escapeNotVerified */ $block->getLinkAttributes() ?>>
<?php
$imgUrl = ???
?>
<?php if ($imgUrl) : ?>

<img width="" src="" class="section-image" alt="" />

<?php endif; ?>

<div class="sect-info">

<h3 class="section-name"><?= $block->escapeHtml($block->getLabel()) ?></h3>

<ul class="section-bullets">
<li>Custom Attribute 1</li>
<li>Custom Attribute 2</li>
<li>etc</li>
</ul>
</div>
</a>
</li>


I have based the Class on the core widget's Link.php, I've previously tried adding in calls to CategoryFactory and so on that I found in examples elsewhere in the hope they would give access to what I need but the most common error I get is "call to undefined method" even for GetName() or getProductCollection() which work elsewhere in the site. I also want to be able to call attributes via GetCustomAttributeName() in the .phtml. Shown here is the code in its closest state to the core widget code (although the GetLabel() is broken here as I'd like to know the steps to build it up to where I want.



How do I call a category (without using the ObjectManager which I've seen is bad) and associated attributes based on the ID which is returned from the widget data?



codeVendorCategoryWidgetBlockWidgetLink.php



 <?php
namespace VendorCategoryWidgetBlockWidget;

use MagentoCatalogUrlRewriteModelProductUrlRewriteGenerator;
use MagentoUrlRewriteModelUrlFinderInterface;
use MagentoUrlRewriteServiceV1DataUrlRewrite;

class Link extends MagentoFrameworkViewElementHtmlLink implements MagentoWidgetBlockBlockInterface
false
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function getHref()

if ($this->_href === null)
if (!$this->getData('id_path'))
throw new RuntimeException('Parameter id_path is not set.');

$rewriteData = $this->parseIdPath($this->getData('id_path'));

$href = false;
$store = $this->hasStoreId() ? $this->_storeManager->getStore($this->getStoreId())
: $this->_storeManager->getStore();
$filterData = [
UrlRewrite::ENTITY_ID => $rewriteData[1],
UrlRewrite::ENTITY_TYPE => $rewriteData[0],
UrlRewrite::STORE_ID => $store->getId(),
];
if (!empty($rewriteData[2]) && $rewriteData[0] == ProductUrlRewriteGenerator::ENTITY_TYPE)
$filterData[UrlRewrite::METADATA]['category_id'] = $rewriteData[2];

$rewrite = $this->urlFinder->findOneByData($filterData);

if ($rewrite)
$href = $store->getUrl('', ['_direct' => $rewrite->getRequestPath()]);

if (strpos($href, '___store') === false)
//$href .= (strpos($href, '?') === false ? '?' : '&') . '___store=' . $store->getCode();


$this->_href = $href;

return $this->_href;


/**
* Parse id_path
*
* @param string $idPath
* @throws RuntimeException
* @return array
*/
protected function parseIdPath($idPath)


/**
* Prepare label using passed text as parameter.
* If anchor text was not specified get entity name from DB.
*
* @return string
*/
public function getLabel()

if (!$this->_anchorText)
if ($this->getData('anchor_text'))
$this->_anchorText = $this->getData('anchor_text');
elseif ($this->_entityResource)
$idPath = explode('/', $this->_getData('id_path'));
if (isset($idPath[1]))
$id = $idPath[1];
if ($id)
$this->_anchorText = $this->_entityResource->getAttributeRawValue(
$id,
'name',
$this->_storeManager->getStore()
);





return $this->_anchorText;


/**
* Render block HTML
* or return empty string if url can't be prepared
*
* @return string
*/
protected function _toHtml()

if ($this->getHref())
return parent::_toHtml();

return 'err';




Thanks for taking the time to read and any guidance you can offer.










share|improve this question







New contributor




rorytec is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


























    0















    I'm trying to build a category link widget similar to the core one, but that can pull in additional information from the category selected, such as the image thumbnail and maybe some custom category attributes we've created. I have created a module that constructs the widget, based on code from the core "Catalog Category Link" widget. That is working well in the Admin side (all widget options are the same as the standard one) and works for creation of a widget that appears on the page, the link works too on the front end. The module is set up with module.xml, registration.php in the usual places.



    codeVendorCategoryWidgetetcwidget.xml



    <?xml version="1.0" encoding="UTF-8"?>
    <widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
    <widget id="tec_catlink" class="VendorCategoryWidgetBlockWidgetLink" placeholder_image="Magento_Catalog::images/category_widget_link.png">
    <label translate="true">Custom Category Link Widget</label>
    <description>Link to specified category to fit with grid</description>
    <parameters>
    <parameter name="id_path" xsi:type="block" visible="true" required="true" sort_order="10">
    <label translate="true">Category</label>
    <block class="MagentoCatalogBlockAdminhtmlCategoryWidgetChooser">
    <data>
    <item name="button" xsi:type="array">
    <item name="open" xsi:type="string" translate="true">Select Category...</item>
    </item>
    </data>
    </block>
    </parameter>
    <parameter name="anchor_text" xsi:type="text" visible="true">
    <label translate="true">Anchor Custom Text</label>
    <description translate="true">If empty, we'll use the category name here.</description>
    </parameter>
    <parameter name="title" xsi:type="text" visible="true">
    <label translate="true">Anchor Custom Title</label>
    </parameter>
    <parameter name="template" xsi:type="select" visible="true">
    <label translate="true">Template</label>
    <options>
    <option name="default"
    value="widget/category_link.phtml"
    selected="true">
    <label translate="true">Grid Link Template</label>
    </option>
    </options>
    </parameter>
    </parameters>
    <containers>
    <container name="content.subcats">
    <template name="grid" value="default" />
    <template name="list" value="list" />
    </container>
    </containers>
    </widget>
    </widgets>


    On the front end the link appears correctly but somehow the function that retrieves the label is broken and only appears if Anchor Text has been entered (looks like $entityresource is empty). In addition I want to be able to call attributes from the category for use on the front end but it seems like I don't have the right dependencies in there or I'm not creating/calling a category object correctly that the core methods will work on (rather than recreating functions).



    codeVendorCategoryWidgetviewfrontendtemplateswidgetcategory_link.phtml



    <?php
    // @codingStandardsIgnoreFile
    ?>

    <li class="subcat-item widget block-category-link">
    <a <?= /* @escapeNotVerified */ $block->getLinkAttributes() ?>>
    <?php
    $imgUrl = ???
    ?>
    <?php if ($imgUrl) : ?>

    <img width="" src="" class="section-image" alt="" />

    <?php endif; ?>

    <div class="sect-info">

    <h3 class="section-name"><?= $block->escapeHtml($block->getLabel()) ?></h3>

    <ul class="section-bullets">
    <li>Custom Attribute 1</li>
    <li>Custom Attribute 2</li>
    <li>etc</li>
    </ul>
    </div>
    </a>
    </li>


    I have based the Class on the core widget's Link.php, I've previously tried adding in calls to CategoryFactory and so on that I found in examples elsewhere in the hope they would give access to what I need but the most common error I get is "call to undefined method" even for GetName() or getProductCollection() which work elsewhere in the site. I also want to be able to call attributes via GetCustomAttributeName() in the .phtml. Shown here is the code in its closest state to the core widget code (although the GetLabel() is broken here as I'd like to know the steps to build it up to where I want.



    How do I call a category (without using the ObjectManager which I've seen is bad) and associated attributes based on the ID which is returned from the widget data?



    codeVendorCategoryWidgetBlockWidgetLink.php



     <?php
    namespace VendorCategoryWidgetBlockWidget;

    use MagentoCatalogUrlRewriteModelProductUrlRewriteGenerator;
    use MagentoUrlRewriteModelUrlFinderInterface;
    use MagentoUrlRewriteServiceV1DataUrlRewrite;

    class Link extends MagentoFrameworkViewElementHtmlLink implements MagentoWidgetBlockBlockInterface
    false
    * @SuppressWarnings(PHPMD.NPathComplexity)
    */
    public function getHref()

    if ($this->_href === null)
    if (!$this->getData('id_path'))
    throw new RuntimeException('Parameter id_path is not set.');

    $rewriteData = $this->parseIdPath($this->getData('id_path'));

    $href = false;
    $store = $this->hasStoreId() ? $this->_storeManager->getStore($this->getStoreId())
    : $this->_storeManager->getStore();
    $filterData = [
    UrlRewrite::ENTITY_ID => $rewriteData[1],
    UrlRewrite::ENTITY_TYPE => $rewriteData[0],
    UrlRewrite::STORE_ID => $store->getId(),
    ];
    if (!empty($rewriteData[2]) && $rewriteData[0] == ProductUrlRewriteGenerator::ENTITY_TYPE)
    $filterData[UrlRewrite::METADATA]['category_id'] = $rewriteData[2];

    $rewrite = $this->urlFinder->findOneByData($filterData);

    if ($rewrite)
    $href = $store->getUrl('', ['_direct' => $rewrite->getRequestPath()]);

    if (strpos($href, '___store') === false)
    //$href .= (strpos($href, '?') === false ? '?' : '&') . '___store=' . $store->getCode();


    $this->_href = $href;

    return $this->_href;


    /**
    * Parse id_path
    *
    * @param string $idPath
    * @throws RuntimeException
    * @return array
    */
    protected function parseIdPath($idPath)


    /**
    * Prepare label using passed text as parameter.
    * If anchor text was not specified get entity name from DB.
    *
    * @return string
    */
    public function getLabel()

    if (!$this->_anchorText)
    if ($this->getData('anchor_text'))
    $this->_anchorText = $this->getData('anchor_text');
    elseif ($this->_entityResource)
    $idPath = explode('/', $this->_getData('id_path'));
    if (isset($idPath[1]))
    $id = $idPath[1];
    if ($id)
    $this->_anchorText = $this->_entityResource->getAttributeRawValue(
    $id,
    'name',
    $this->_storeManager->getStore()
    );





    return $this->_anchorText;


    /**
    * Render block HTML
    * or return empty string if url can't be prepared
    *
    * @return string
    */
    protected function _toHtml()

    if ($this->getHref())
    return parent::_toHtml();

    return 'err';




    Thanks for taking the time to read and any guidance you can offer.










    share|improve this question







    New contributor




    rorytec is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      0












      0








      0








      I'm trying to build a category link widget similar to the core one, but that can pull in additional information from the category selected, such as the image thumbnail and maybe some custom category attributes we've created. I have created a module that constructs the widget, based on code from the core "Catalog Category Link" widget. That is working well in the Admin side (all widget options are the same as the standard one) and works for creation of a widget that appears on the page, the link works too on the front end. The module is set up with module.xml, registration.php in the usual places.



      codeVendorCategoryWidgetetcwidget.xml



      <?xml version="1.0" encoding="UTF-8"?>
      <widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
      <widget id="tec_catlink" class="VendorCategoryWidgetBlockWidgetLink" placeholder_image="Magento_Catalog::images/category_widget_link.png">
      <label translate="true">Custom Category Link Widget</label>
      <description>Link to specified category to fit with grid</description>
      <parameters>
      <parameter name="id_path" xsi:type="block" visible="true" required="true" sort_order="10">
      <label translate="true">Category</label>
      <block class="MagentoCatalogBlockAdminhtmlCategoryWidgetChooser">
      <data>
      <item name="button" xsi:type="array">
      <item name="open" xsi:type="string" translate="true">Select Category...</item>
      </item>
      </data>
      </block>
      </parameter>
      <parameter name="anchor_text" xsi:type="text" visible="true">
      <label translate="true">Anchor Custom Text</label>
      <description translate="true">If empty, we'll use the category name here.</description>
      </parameter>
      <parameter name="title" xsi:type="text" visible="true">
      <label translate="true">Anchor Custom Title</label>
      </parameter>
      <parameter name="template" xsi:type="select" visible="true">
      <label translate="true">Template</label>
      <options>
      <option name="default"
      value="widget/category_link.phtml"
      selected="true">
      <label translate="true">Grid Link Template</label>
      </option>
      </options>
      </parameter>
      </parameters>
      <containers>
      <container name="content.subcats">
      <template name="grid" value="default" />
      <template name="list" value="list" />
      </container>
      </containers>
      </widget>
      </widgets>


      On the front end the link appears correctly but somehow the function that retrieves the label is broken and only appears if Anchor Text has been entered (looks like $entityresource is empty). In addition I want to be able to call attributes from the category for use on the front end but it seems like I don't have the right dependencies in there or I'm not creating/calling a category object correctly that the core methods will work on (rather than recreating functions).



      codeVendorCategoryWidgetviewfrontendtemplateswidgetcategory_link.phtml



      <?php
      // @codingStandardsIgnoreFile
      ?>

      <li class="subcat-item widget block-category-link">
      <a <?= /* @escapeNotVerified */ $block->getLinkAttributes() ?>>
      <?php
      $imgUrl = ???
      ?>
      <?php if ($imgUrl) : ?>

      <img width="" src="" class="section-image" alt="" />

      <?php endif; ?>

      <div class="sect-info">

      <h3 class="section-name"><?= $block->escapeHtml($block->getLabel()) ?></h3>

      <ul class="section-bullets">
      <li>Custom Attribute 1</li>
      <li>Custom Attribute 2</li>
      <li>etc</li>
      </ul>
      </div>
      </a>
      </li>


      I have based the Class on the core widget's Link.php, I've previously tried adding in calls to CategoryFactory and so on that I found in examples elsewhere in the hope they would give access to what I need but the most common error I get is "call to undefined method" even for GetName() or getProductCollection() which work elsewhere in the site. I also want to be able to call attributes via GetCustomAttributeName() in the .phtml. Shown here is the code in its closest state to the core widget code (although the GetLabel() is broken here as I'd like to know the steps to build it up to where I want.



      How do I call a category (without using the ObjectManager which I've seen is bad) and associated attributes based on the ID which is returned from the widget data?



      codeVendorCategoryWidgetBlockWidgetLink.php



       <?php
      namespace VendorCategoryWidgetBlockWidget;

      use MagentoCatalogUrlRewriteModelProductUrlRewriteGenerator;
      use MagentoUrlRewriteModelUrlFinderInterface;
      use MagentoUrlRewriteServiceV1DataUrlRewrite;

      class Link extends MagentoFrameworkViewElementHtmlLink implements MagentoWidgetBlockBlockInterface
      false
      * @SuppressWarnings(PHPMD.NPathComplexity)
      */
      public function getHref()

      if ($this->_href === null)
      if (!$this->getData('id_path'))
      throw new RuntimeException('Parameter id_path is not set.');

      $rewriteData = $this->parseIdPath($this->getData('id_path'));

      $href = false;
      $store = $this->hasStoreId() ? $this->_storeManager->getStore($this->getStoreId())
      : $this->_storeManager->getStore();
      $filterData = [
      UrlRewrite::ENTITY_ID => $rewriteData[1],
      UrlRewrite::ENTITY_TYPE => $rewriteData[0],
      UrlRewrite::STORE_ID => $store->getId(),
      ];
      if (!empty($rewriteData[2]) && $rewriteData[0] == ProductUrlRewriteGenerator::ENTITY_TYPE)
      $filterData[UrlRewrite::METADATA]['category_id'] = $rewriteData[2];

      $rewrite = $this->urlFinder->findOneByData($filterData);

      if ($rewrite)
      $href = $store->getUrl('', ['_direct' => $rewrite->getRequestPath()]);

      if (strpos($href, '___store') === false)
      //$href .= (strpos($href, '?') === false ? '?' : '&') . '___store=' . $store->getCode();


      $this->_href = $href;

      return $this->_href;


      /**
      * Parse id_path
      *
      * @param string $idPath
      * @throws RuntimeException
      * @return array
      */
      protected function parseIdPath($idPath)


      /**
      * Prepare label using passed text as parameter.
      * If anchor text was not specified get entity name from DB.
      *
      * @return string
      */
      public function getLabel()

      if (!$this->_anchorText)
      if ($this->getData('anchor_text'))
      $this->_anchorText = $this->getData('anchor_text');
      elseif ($this->_entityResource)
      $idPath = explode('/', $this->_getData('id_path'));
      if (isset($idPath[1]))
      $id = $idPath[1];
      if ($id)
      $this->_anchorText = $this->_entityResource->getAttributeRawValue(
      $id,
      'name',
      $this->_storeManager->getStore()
      );





      return $this->_anchorText;


      /**
      * Render block HTML
      * or return empty string if url can't be prepared
      *
      * @return string
      */
      protected function _toHtml()

      if ($this->getHref())
      return parent::_toHtml();

      return 'err';




      Thanks for taking the time to read and any guidance you can offer.










      share|improve this question







      New contributor




      rorytec is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.












      I'm trying to build a category link widget similar to the core one, but that can pull in additional information from the category selected, such as the image thumbnail and maybe some custom category attributes we've created. I have created a module that constructs the widget, based on code from the core "Catalog Category Link" widget. That is working well in the Admin side (all widget options are the same as the standard one) and works for creation of a widget that appears on the page, the link works too on the front end. The module is set up with module.xml, registration.php in the usual places.



      codeVendorCategoryWidgetetcwidget.xml



      <?xml version="1.0" encoding="UTF-8"?>
      <widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
      <widget id="tec_catlink" class="VendorCategoryWidgetBlockWidgetLink" placeholder_image="Magento_Catalog::images/category_widget_link.png">
      <label translate="true">Custom Category Link Widget</label>
      <description>Link to specified category to fit with grid</description>
      <parameters>
      <parameter name="id_path" xsi:type="block" visible="true" required="true" sort_order="10">
      <label translate="true">Category</label>
      <block class="MagentoCatalogBlockAdminhtmlCategoryWidgetChooser">
      <data>
      <item name="button" xsi:type="array">
      <item name="open" xsi:type="string" translate="true">Select Category...</item>
      </item>
      </data>
      </block>
      </parameter>
      <parameter name="anchor_text" xsi:type="text" visible="true">
      <label translate="true">Anchor Custom Text</label>
      <description translate="true">If empty, we'll use the category name here.</description>
      </parameter>
      <parameter name="title" xsi:type="text" visible="true">
      <label translate="true">Anchor Custom Title</label>
      </parameter>
      <parameter name="template" xsi:type="select" visible="true">
      <label translate="true">Template</label>
      <options>
      <option name="default"
      value="widget/category_link.phtml"
      selected="true">
      <label translate="true">Grid Link Template</label>
      </option>
      </options>
      </parameter>
      </parameters>
      <containers>
      <container name="content.subcats">
      <template name="grid" value="default" />
      <template name="list" value="list" />
      </container>
      </containers>
      </widget>
      </widgets>


      On the front end the link appears correctly but somehow the function that retrieves the label is broken and only appears if Anchor Text has been entered (looks like $entityresource is empty). In addition I want to be able to call attributes from the category for use on the front end but it seems like I don't have the right dependencies in there or I'm not creating/calling a category object correctly that the core methods will work on (rather than recreating functions).



      codeVendorCategoryWidgetviewfrontendtemplateswidgetcategory_link.phtml



      <?php
      // @codingStandardsIgnoreFile
      ?>

      <li class="subcat-item widget block-category-link">
      <a <?= /* @escapeNotVerified */ $block->getLinkAttributes() ?>>
      <?php
      $imgUrl = ???
      ?>
      <?php if ($imgUrl) : ?>

      <img width="" src="" class="section-image" alt="" />

      <?php endif; ?>

      <div class="sect-info">

      <h3 class="section-name"><?= $block->escapeHtml($block->getLabel()) ?></h3>

      <ul class="section-bullets">
      <li>Custom Attribute 1</li>
      <li>Custom Attribute 2</li>
      <li>etc</li>
      </ul>
      </div>
      </a>
      </li>


      I have based the Class on the core widget's Link.php, I've previously tried adding in calls to CategoryFactory and so on that I found in examples elsewhere in the hope they would give access to what I need but the most common error I get is "call to undefined method" even for GetName() or getProductCollection() which work elsewhere in the site. I also want to be able to call attributes via GetCustomAttributeName() in the .phtml. Shown here is the code in its closest state to the core widget code (although the GetLabel() is broken here as I'd like to know the steps to build it up to where I want.



      How do I call a category (without using the ObjectManager which I've seen is bad) and associated attributes based on the ID which is returned from the widget data?



      codeVendorCategoryWidgetBlockWidgetLink.php



       <?php
      namespace VendorCategoryWidgetBlockWidget;

      use MagentoCatalogUrlRewriteModelProductUrlRewriteGenerator;
      use MagentoUrlRewriteModelUrlFinderInterface;
      use MagentoUrlRewriteServiceV1DataUrlRewrite;

      class Link extends MagentoFrameworkViewElementHtmlLink implements MagentoWidgetBlockBlockInterface
      false
      * @SuppressWarnings(PHPMD.NPathComplexity)
      */
      public function getHref()

      if ($this->_href === null)
      if (!$this->getData('id_path'))
      throw new RuntimeException('Parameter id_path is not set.');

      $rewriteData = $this->parseIdPath($this->getData('id_path'));

      $href = false;
      $store = $this->hasStoreId() ? $this->_storeManager->getStore($this->getStoreId())
      : $this->_storeManager->getStore();
      $filterData = [
      UrlRewrite::ENTITY_ID => $rewriteData[1],
      UrlRewrite::ENTITY_TYPE => $rewriteData[0],
      UrlRewrite::STORE_ID => $store->getId(),
      ];
      if (!empty($rewriteData[2]) && $rewriteData[0] == ProductUrlRewriteGenerator::ENTITY_TYPE)
      $filterData[UrlRewrite::METADATA]['category_id'] = $rewriteData[2];

      $rewrite = $this->urlFinder->findOneByData($filterData);

      if ($rewrite)
      $href = $store->getUrl('', ['_direct' => $rewrite->getRequestPath()]);

      if (strpos($href, '___store') === false)
      //$href .= (strpos($href, '?') === false ? '?' : '&') . '___store=' . $store->getCode();


      $this->_href = $href;

      return $this->_href;


      /**
      * Parse id_path
      *
      * @param string $idPath
      * @throws RuntimeException
      * @return array
      */
      protected function parseIdPath($idPath)


      /**
      * Prepare label using passed text as parameter.
      * If anchor text was not specified get entity name from DB.
      *
      * @return string
      */
      public function getLabel()

      if (!$this->_anchorText)
      if ($this->getData('anchor_text'))
      $this->_anchorText = $this->getData('anchor_text');
      elseif ($this->_entityResource)
      $idPath = explode('/', $this->_getData('id_path'));
      if (isset($idPath[1]))
      $id = $idPath[1];
      if ($id)
      $this->_anchorText = $this->_entityResource->getAttributeRawValue(
      $id,
      'name',
      $this->_storeManager->getStore()
      );





      return $this->_anchorText;


      /**
      * Render block HTML
      * or return empty string if url can't be prepared
      *
      * @return string
      */
      protected function _toHtml()

      if ($this->getHref())
      return parent::_toHtml();

      return 'err';




      Thanks for taking the time to read and any guidance you can offer.







      magento2 category category-attribute






      share|improve this question







      New contributor




      rorytec is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      rorytec is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      rorytec is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked Apr 25 at 12:19









      rorytecrorytec

      11




      11




      New contributor




      rorytec is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      rorytec is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      rorytec is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          0






          active

          oldest

          votes












          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "479"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          rorytec is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f272439%2fmagento2-how-to-build-a-custom-category-link-widget-with-attributes%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          rorytec is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          rorytec is a new contributor. Be nice, and check out our Code of Conduct.












          rorytec is a new contributor. Be nice, and check out our Code of Conduct.











          rorytec is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f272439%2fmagento2-how-to-build-a-custom-category-link-widget-with-attributes%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown