Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In CakePHP, how can you determine if a field was changed in an edit action?

Tags:

php

cakephp

I'm using the cacheCounter in CakePHP, which increments a counter for related fields.

Example, I have a Person table a Source table. Person.source_id maps to a row in the Source table. Each person has one Source, and each Source has none or many Person rows.

cacheCounter is working great when I change the value of a source on a person. It increments Source.Person_Count. Cool.

But when it increments, it adds it to the destination source for a person, but doesn't remove it from the old value. I tried updateCacheControl() in afterSave, but that didn't do anything.

So then I wrote some code in my model for afterSave that would subtract the source source_id, but it always did this even when I wasn't even changing the source_id. (So the count went negative).

My question: Is there a way to tell if a field was changed in the model in CakePHP?

like image 560
Justin Avatar asked Sep 22 '08 15:09

Justin


2 Answers

To monitor changes in a field, you can use this logic in your model with no changes elsewhere required:

function beforeSave() {
    $this->recursive = -1;
    $this->old = $this->find(array($this->primaryKey => $this->id));
    if ($this->old){
        $changed_fields = array();
        foreach ($this->data[$this->alias] as $key =>$value) {
            if ($this->old[$this->alias][$key] != $value) {
                $changed_fields[] = $key;
            }
        }
    }
    // $changed_fields is an array of fields that changed
    return true;
}
like image 103
Alexander Morland Avatar answered Oct 28 '22 05:10

Alexander Morland


With reference to Alexander Morland Answer.

How about this instead of looping through it in before filter.

$result = array_diff_assoc($this->old[$this->alias],$this->data[$this->alias]);

You will get key as well as value also.

like image 36
Vins Avatar answered Oct 28 '22 06:10

Vins