2

I'm new to Yii, and i am struggling with the display of some classes. I have a very basic example:

I got my template file: themes/classic/views/layout/main.php and i want to call a class there.

<div class="col-lg-2 col-md-2 col-sm-2">
    <div class="box">
        <h2>Categorieën</h2>
        <p>
            <?php
            echo AdminController::producten(); //<--- this does not work!
            ?>
        </p>
    </div><!-- box -->
</div><!-- col-lg-2 -->

The class is protected/controllers/AdminController.php

In that class i have a function called producten()

public function producten(){
    return 'Hier komen categorieën!';
}

I want to view that function (in this case a string) in my template page.

Can you guys show me how, if this is possible ofcourse. Or should i use a widget?

Refilon
  • 3,334
  • 1
  • 27
  • 51

1 Answers1

1

In order to make below code working:

echo AdminController::producten();

You need to change your method to static method like below:

public static function producten(){
    return 'Hier komen categorieën!';
}

On the other hand, if your controller is extended from a base controller which holds your main layout, you can use $this keyword to get a method.

When you install a fresh yii web application base controller is under /protected/components/Controller.php which all controllers will extend that. So if you put your method in that Controller, it will be accessible via all controller which are extended from base controller.

Ali MasudianPour
  • 14,329
  • 3
  • 60
  • 62
  • This does not work. I'm in a theme file not in the controller page itself. So how do i call another class inside another page? – Refilon Nov 03 '14 at 10:09
  • @Deer-Outdoor.nl under all conditions, you will use this theme in a controller. You will never user that theme file alone. Also, In each view `$this` refers to controller which rendered view. You can define your method in your base controller and use it under theme main file by `$this->methodName()` – Ali MasudianPour Nov 03 '14 at 10:14
  • I see what you mean. If i go to the admincontroller page, it works. But i want it to also work when i'm lets say in the site controller. But that does not work. How can i fix this? – Refilon Nov 03 '14 at 10:17
  • Do you have a base controller which you defined your main layout? When you install a fresh yii web application it is under `/protected/components/Controller.php` which all controllers will extend that. So if you put your method in that Controller, it is accessible via all controller which are extended from that. – Ali MasudianPour Nov 03 '14 at 10:19
  • You rock @Ali! That worked! I put the function inside the controller class, and now i can see it everywhere! Thanks man! – Refilon Nov 03 '14 at 10:22
  • Can you also help me with this question? http://stackoverflow.com/questions/26757267/category-hierarchy-php-mysql-in-yii – Refilon Nov 06 '14 at 12:15