Search code examples
phpyii2yii2-extension

Yii2 custom widget assets not registering


I'm trying to develop a custom widget, but I've run into a wall. I have some third-party JS/CSS files I need to include, but for whatever reason, Yii2 will not register them. I've followed everything in the Yii2 documentation but seem to get nowhere. My directory structure is as follows:

components
 - DildenFeedback.php
 - DildenFeedbackAsset.php
 - views/
  -- feedback.php
 - assets/
  -- feedback.min.js
  -- feedback.min.css

DildenFeedback.php (Widget Class)

<?php

namespace app\components\yii2feedbackwidget;

use Yii;
use yii\base\Widget;
use app\components\yii2feedbackwidget\DildenFeedbackAsset;

class DildenFeedback extends Widget
{

    public function run() {
        parent::run();
        DildenFeedbackAsset::register($this->view);
        return $this->render('feedback');
    }
}

DildenFeedbackAsset.php (Widget Asset Class)

<?php

namespace app\components\yii2feedbackwidget;
use yii\web\AssetBundle;

class DildenFeedbackAsset extends AssetBundle {

    public $sourcePath = 'assets/';

    public $css = ['assets/feedback.min.css'];
    public $js = ['assets/feedback.min.js'];

    public $depends = ['yii\web\JqueryAsset'];
}

Feedback View

?>
<script type="text/javascript">
    $.feedback();
</script>

views/layouts/main.php (The main template I was trying to call in)

<?php $this->endBody() ?>
<?php
    echo DildenFeedback::widget();
?>

So when I go to inspect the page, feedback.min.js/css are nowhere to be found. The view file is rendered correctly, but my guess is that my AssetBundle is improperly formed. Any help would be much appreciated.

EDIT (From the Yii Debugger Assets):
sourcePath /var/www/public/components/yii2feedbackwidget/assets
basePath /var/www/public/web/assets/7e80049a
baseUrl /assets/7e80049a
css assets/feedback.min.css
js assets/feedback.min.js
depends yii\web\JqueryAsset

EDIT 2 I have tested this on a fresh install of Yii2, and I get the same error.


Solution

  • I've solved it, and I feel a bit silly. What it came down to, was the location of the widget call. As I noted in my original question, I was echoing the widget like so:

    <?php $this->endBody() ?>
    <?php
        echo DildenFeedback::widget();
    ?>
    

    However, I did not pay attention to where that call was. It NEEDS to be before the endBody call

    <?php
        echo DildenFeedback::widget();
    ?>
    <?php $this->endBody() ?>
    

    This ended up solving the issue. Thanks to Soju for directing me towards the widget call.