T
T
TORyii22021-10-07 12:16:27
Yii
TORyii2, 2021-10-07 12:16:27

Yii2 How to add images to the link in the Menu widget (links are loaded from the database)?

It is necessary that pictures of each item of the

view menu be uploaded with links:

<?php 

      echo Menu::widget([
  'menuKey' => '1',

       'options' => [
          'id'=>'navid',
          'class' => 'nav spacer',
        
          'data'=>'menu',
        ],

'linkTemplate' => '<nav class="nav spacer"><a href="{url}">{image}{label}</a></nav>',
    'activeCssClass'=>'active',
    'encodeLabels' =>'false',
  'itemOptions' => ['class' => 'nav__link'],
        'submenuTemplate' => "<ul class = 'droplink active open dropdown-menu' role = 'menu'> \ n {items} \ n </ul>",
]);
    

?>


wigjet :
<?php

namespace frontend\widgets;


class Menu extends \yii\widgets\Menu
{
  /**
   * @var integer|null $menuKey Ключ используемого меню для построения структуры в $items
   */
  public $menuKey;
  /**
   * {@inheritdoc}
   */
  public function run()
  {
    if (!empty($this->menuKey)) {
      $this->loadItems();
    }

    return parent::run();
  }

  /**
   * @return void
   */
  protected function loadItems()
  {
    if (!empty($this->menuKey)) {
      $this->items = [];

      $menu = \common\models\Menu::find()
        ->active()
        ->andWhere(['key' => $this->menuKey])
        ->one()
      ;

      if (empty($menu)) {
        return;
      }

      foreach ($menu->getItems()
        ->active()
        ->roots()
        ->orderBy(['order' => SORT_ASC])
        ->all()
      as $item) {
        $this->items[] = $this->getMenuItemTree($item);
      }
    }
  }

  /**
   * @param \common\models\MenuItem $item
   * @return array
   */
  protected function getMenuItemTree(\common\models\MenuItem $item)
  {
    $tree = ['label' => $item->label, 'url' => $item->url, 'image'=>$item->image];

    $children = $item->getChildren()
      ->active()
      ->orderBy(['order' => SORT_ASC])
      ->all()
    ;

    if (!empty($children)) {
      $childTree = [];

      foreach ($children as $child) {
        $childTree[] = $this->getMenuItemTree($child);
      }

      $tree['items'] = $childTree;
    }

    return $tree;
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question