We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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.



2.1k

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?



33.8k

Inside validation:

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


2.1k
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.



33.8k

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

A previous IF with it will work perfectly. Thanks.



1.3k
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 ?