Mostafa Abedi
Mostafa Abedi

Reputation: 541

How can i access my custom widget in view file in yii2

This is my custom widget (vendor\sliderWidget.php):

    <?php
namespace Mostafa;
use yii;

  class sliderWidget extends \yii\base\Widget {
    public function init() {
      parent::init();
 ...

But when i try to use this widget in view file (frontend\views\site\index.php ):

<?php

use yii\helpers\Html;
use kartik\icons\Icon;
 ?>

<?= \Mostafa\sliderWidget::widget();?>
 ...

I got the

PHP Fatal Error – yii\base\ErrorException Class 'Mostafa\sliderWidget' not found error

It seems the problem is autoloading. How should i resolve this problem.

Upvotes: 2

Views: 672

Answers (1)

Bizley
Bizley

Reputation: 18021

Place your folder with widget outside vendor folder and use PSR-4 standard.

If this is based on Basic Project Template you can put it in root folder like /Mostafa. If this is based on Advanced Project Template you can put it in one of the application's folder like /frontend/Mostafa.

Name the widget class inside Mostafa folder properly like SliderWidget.php and name the class inside properly (SliderWidget).

In this file use proper namespace: for Basic it's namespace app\Mostafa;, for Advanced in the example it's namespace frontend\Mostafa;

Now you can use this widget properly. For Basic:

<?= \app\Mostafa\SliderWidget::widget() ?>

For Advanced in the example:

<?= \frontend\Mostafa\SliderWidget::widget() ?>

Upvotes: 1

Related Questions