Search code examples
phpyii2breadcrumbs

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

Solution

  • 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.