DaveR
DaveR

Reputation: 2483

Trying to create model on page view in Yii

When someone views a page of my site, I'd like to save some information about the visit in my Event table.

At the moment I have this code in my view - but I don't seem to get any data saved to the database -

if(!Yii::app()->user->isGuest) {
$lview=new Event;
$lview->userid=Yii::app()->user->id;
$lview->type="lview";
$lview->data=$model->id;
$lview->event="view";
$lview->save();
}

is it possible/advisable to create objects in this way?

Upvotes: 1

Views: 463

Answers (1)

bool.dev
bool.dev

Reputation: 17478

Only thing advisable to do would be to save the data in the controller. For separation of concerns.

As every view, in the normal process is "rendered" using $this->render('view'); anyway, you should do this process of saving before this render call, in the action.

As for the saving issue check the errors using $lview->getErrors();, and debug from there:

public function actionShowSomeView(){
    // initialize your model here

    if(!Yii::app()->user->isGuest) {
        $lview=new Event;
        // assign values to $lview
        if(!$lview->save()){
            CVarDumper::dump($lview->getErrors());;
        }
    }

    // do your other stuff

    $this->render('view');
}

Upvotes: 2

Related Questions