2

When I try to redirect to url from the my controller's init() function, I get this message Call to a member function redirect() on string.

public function init()
{
    $someCondition = myBoolFunction();
    if ($someCondition) {
        return $this->redirect('my/url'));
    }

    parent::init();
}
Martin
  • 23
  • 5

1 Answers1

5

You need to call $this->redirect() after parent::init(), since $response property (used by $this->redirect()) is initialized there.

public function init() {
    parent::init();

    $someCondition = myBoolFunction();
    if ($someCondition) {
        return $this->redirect('my/url'));
    }
}

But in general init() is not a good place to do such redirection (it probably won't even work, since init() shouldn't return anything, so your redirection may be ignored), you should use beforeAction() instead. Here you can see how to configure response in beforeAction(), just replace asJson() with your redirection:

public function beforeAction() {
    parent::init();

    $someCondition = myBoolFunction();
    if ($someCondition) {
        $this->redirect('my/url'));
        return false;
    }

    return parent::beforeAction();
}
rob006
  • 21,383
  • 5
  • 53
  • 74