Dmitry
Dmitry

Reputation: 123

Yii2 Set page title from component view

I have page, for example, /about.

In page's view i may set page title: $this->title = "abc" - it works ok.

Also i have Header component in /components with his own view /components/views/Header.php

How could I change my page title from my component's view? $this->title does not work because I'm in component's view, not page.

Upvotes: 2

Views: 4754

Answers (2)

Igbanam
Igbanam

Reputation: 6082

Embed the page object into the component. Then change the properties of the page object through the aggregation composition.

The component class would read something like...

class MyComponent extends Component
{
    private $pageObject;
    public $title;

    public function __construct(yii\web\View $view)
    {
        $this->pageObject = $view;
    }

    // this would change the title of the component
    public function setTitle(string $newTitle)
    {
        $this->title = $newTitle;
    }

    public function changePageTitle(string $newTitle)
    {
        $this->pageObject->title = $newTitle;
    }
}

Where, if you're in a view and you want to use your component in that view, you can instantiate it using

$comp = new MyComponent($this);
// where `$this` is the current page object

Now, from the component scope, $this->title = 'bleh'; would change the title of the component while $this->changePageTitle('bleh'); would change the page's title.

Upvotes: 1

Clyff
Clyff

Reputation: 4076

Not sure how you are calling your component, but to change the title you need to specify you want to change the current view.

Here is an example, in the view add something like (or use any method you already used but make sure you insert the view as a parameter):

MyComponent::changeTitle($this);

And in your component (whatever method you want to do this):

public static function changeTitle($view)
{
    $view->title = 'changed';
}

If this is not related with your situation, please add an example of the view and the component so we can understand better what is the scenario.

Upvotes: 2

Related Questions