Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Setting snapshot of new model

How I can set a snapshot of a new model? I tried this:

public function initialize()
{
    $this->keepSnapshots(true);
    $this->useDynamicUpdate(true);
    $this->setSnapshotData([
        'field1' => $this->field1,
        ...
    ]);
}

But I just get Change checking cannot be performed because the object has not been persisted or is deleted when I do $this->hasChanged("field1") in validation() event.

I remark that, as a new model, its values are initially NULL, so I think that the problem is that. I also tried with "", but is the same.



1.4k

snapshots data are automatically set when you fetch from the database with keepsnapshots.

so there is no need to set snapshotdata.

could you provide the code you are using for validation?



18.5k

Inside validation:

// The problem is the IF.
if ($this->hasChanged("field1"))
{
    // Do some stuff.
}


1.4k
Accepted
answer

Snapshots are automatically captured when you retrieve from database.

So the only way has change will work is.

$obj = Model::findFirst(1) $obj->id = 2;

if($obj->hasChanged("id")) { // will be true. }

if you are using it as $obj = new Model();

you cannot use obj->hasChanged as the snapshot data is not available and is not a valid database entry.



18.5k

Ok, so it was about the index. Now I undestand.

A previous IF with it will work perfectly. Thanks.



803
edited May '15

I've got same error on hasChanged() here, since the $this->customer is a relational alias, and got changed as below

public function afterSave()
{
    if($this->hasSnapshotData()){
        $dataold = $this->getSnapshotData();
        if(!$dataold['verified'] && $this->verified && !is_object($this->verified)){
            $customer = $this->customer;
            if($this->customerId && !$customer->status){
                $customer->status = 1;
                $customer->save();
            }
        }

        //update log
        if($this->hasChanged()){
            $this->logUpdate(new CustomerCollections);
        }
    }elseif($this->id){

    //insert logger
    $this->logInsert(new CustomerCollections);
    }
}

I've got Change checking cannot be performed because the object has not been persisted or is deleted on checking hasChanged any suggestion ?