Bird87 ZA
Bird87 ZA

Reputation: 2160

Detecting field changes - cakePHP

What I want

I want to see which fields on a table was changed and save that name into the database under the edit column.

What I have

Currently, not much. Just the standard cakePHP baked edit view and controller. I have done it previously, but not with cakePHP. What I did was retrieve the record, and if it's different to what the user entered, save the name of the column that was edited in the edit column corresponding to the row.

My Question

Could someone tell me how I would compare user input with what is on the database?

Upvotes: 0

Views: 230

Answers (1)

mark
mark

Reputation: 21743

Behaviors like the "Logable" Behavior already do that and store the information separately. I advice you to do the same. the "changes" do not necessarily need to be put into the same table. If you feel they do, though, you could make your own "modified" Logable behavior that only creates the "diff" and stores it into a field of your choice on the same record.

PS: You might also want to take a look at the RevisionBehavior. It also contains some diff algorithm. Then there is the WhoDidIt behavior which stores the user that last modified the record. In the same table, though. So this combined with the above should do the trick.

Either way:

  • use callbacks (beforeSave/afterSave) on model itself or (cleaner) as behavior
  • calculate diff
  • store the diff in a separate table or as in your case in an extra table field.

Actually writing something up here that does the job is pretty straight-forward. The voluntary exercise here would be to write it more "generic". Maybe you want to reuse the same functionality again for other models in the future? Copy-and-paste would be pretty bad style then. The goal here would be to create some generic piece of code you can easily reuse. If your initial code works, try to rewrite it into a generic ChangesBehavior that you can attach to as many models you like. You can take the linked examples or take a look at other behaviors out there to get an idea how to do that.

Also you can publish your behavior in github/plugins.cakephp and give the community something back again. Maybe others find it useful, too.

Upvotes: 3

Related Questions