Search code examples
postyii2load

Yii2 Call to a member function load() on a non-object


I have standard code in controller for User class

public function actionEdit($username)
    {
...
        $model = User::findByUsername($username);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {

And if I edit user I get error

Call to a member function load() on a non-object 

which is pointing at $model->load

Why is that ?

UPDATE

var_dump on $model shows NULL which is strange

because I have the same function used in view action and it works perfectly

public function actionView($username){
    $model = User::findByUsername($username);
   if($model){

UPDATE2 I've made some changes now the code is like this, no errors but the logic goes that there is no load and save, cause if goes to else section and edit is loaded again not view.

$model = User::findByUsername($username);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'username' => $model->username]);
        } else {
return $this->render('edit', [
                'model' => $model,
}

Solution

  • Use

    var_dump($model);
    

    To see what exacly $model is. Propably it's not a model, check what's result of function findByUsername()