4

there's a small, but very important difference, between calling clear() and create() within a loop:

let's assume the following code:

foreach ($posts as $post) {
  $this->Post->create();
  $this->Post->id = $post['Post']['id'];
  $this->Post->save(['column3' => 'foo', 'column4' => 'bar']);
}

When doing a create(): column 1, which might default to boolean false, is magically added to the updated-fields as well and can lead to a data loss (think of post with column1 = true).

When doing a clear() instead of create(): column 1, which is not mentioned in the save-statement is not touched at all.

So, is it always safe to rely on clear() in a foreach, where existing data is partially updated?

Second party of my question: Is it ALWAYS better to rely on clear()? (When looking at the code of clear(), you see, that it's only a convenience wrapper for create(false)). And the only difference in create() and create(false) is the initialization of the default values. I think, default values should better be set directly on database-level.

Btw: I just proposed a small doc change. Feel free to +1 this:

AD7six
  • 63,116
  • 12
  • 91
  • 123
Johannes N.
  • 2,364
  • 3
  • 28
  • 45

1 Answers1

7

So, is it always safe to rely on clear() in a foreach, where existing data is partially updated?

Yes.

Is it ALWAYS better to rely on clear()?

The only benefit of using create() when adding records is your form will be pre-populated with default values to be shown to user. So if you don't care about this you can always use clear().

ADmad
  • 8,102
  • 16
  • 18