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

hasChanged ans int value

When i keepSnapshots and i check getChangedFields() in my model and i try to save model with int value, even if it's the same it's shows me that value was changed and when i try to check string, it work. Field isOutstanding in mysql database is smallint type. Example.

$transaction = MyTransaction::findFirst(1);
$transaction->isOutstanding = 0;
$transaction->save();

My getChangedFields function shows that isOutstanding field was changed, even if it's not, because orginal value is 0.

If i check in that way, then it's work

$transaction = MyTransaction::findFirst(1);
$transaction->isOutstanding = '0';
$transaction->save();

How can i check changing int or decimal values using function getChangedFields , or hasChanged ??

Hi @hajcu better use setter to take more control of data

class MyTransaction extends Model {
    public function setOutstanding(int $value) {
        $this->isOutstanding = abs($value);
    }
}

Now you always are right if value has changed or not

Good luck



8.7k
edited Oct '17

This was not my question. The functionality look like this: i need to have info, in one of column, with information if outstanding amount was change so:

$transaction->outstandingAmount = 200;
$transaction->save();

Then in function beforeSave for example, i need to have trigger simialr to this:

if($this->hasChanged(['outstandingAmount']){
    $this->isOutstanding = 1;
}

But as i wrote before, when outstandingAmount was 200, and i once again save 200, then phalcon show that this column was changed, but it's not true, because valu was exacly the same.

Well you can do your own "manager" of changes

class YourModel extends Model {
    public function initialize() {
        $this->keepSnapshots(true); // keep original data
    }

    // before create or update
    public function beforeSave() {
        $data = $this->getSnapshotData(); 

        if ($data['outstandingAmount'] !== $this->outstandingAmount) {
            $this->isOutstanding = 1;
        }       
    }
}

Then if you like you can create your own behavior with that

Good luck



8.7k
Accepted
answer
edited Oct '17

Nope, unfortunetly snapshotdata return all values as string type, and this is the final code, that realy work

public function beforeSave() {
        $data = $this->getOldSnapshotData();

        if(floatval($this->outstandingAmount) <> 0){
            $this->isOutstanding = 1;
        }else{
            $this->isOutstanding = 0;
        }

        if (floatval($data['outstandingAmount']) != floatval($this->outstandingAmount)) {
            $this->isOutstandingChange = 1;
        }
    }