Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building breadcrumbs automatically with modules

My web page has multiple modules, and i want to know if there is a way to add breadcrumbs the modules home url, without have to add manually to all files. ex:

Home > MyModule > MyController
like image 752
rob180 Avatar asked Sep 27 '22 19:09

rob180


1 Answers

The question is definetely too broad, but here is solution I used:

<?php

namespace backend\modules\tests\components;

use yii\helpers\ArrayHelper;
use yii\web\Controller as BaseController;
use yii\web\View;

class Controller extends BaseController
{   
    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {
            Yii::$app->view->on(View::EVENT_BEGIN_BODY, function () {
                $this->fillBreadcrumbs();
            });

            return true;
        } else {
            return false;
        }
    }

    /**
     * Fill common breadcrumbs
     */
    protected function fillBreadcrumbs()
    {
        $breadcrumbs = [];

        // Add needed elements to $breadcrumbs below

        $label = 'Tests';
        $breadcrumbs[] = $this->route == '/tests/default/index' ? $label : [
            'label' => $label,
            'url' => ['/tests/default/index'],
        ];

        // ...

        $this->mergeBreadCrumbs($breadcrumbs);
    }

    /**
     * Prepend common breadcrumbs to existing ones
     * @param array $breadcrumbs
     */
    protected function mergeBreadcrumbs($breadcrumbs)
    {
        $existingBreadcrumbs = ArrayHelper::getValue($this->view->params, 'breadcrumbs', []);
        $this->view->params['breadcrumbs'] = array_merge($breadcrumbs, $existingBreadcrumbs);
    }
}

As you can see, it's based on view events and custom controller (extending from yii\web\Controller).

All you need next is to extend needed controllers from custom one.

like image 124
arogachev Avatar answered Nov 12 '22 21:11

arogachev