I have a simple table with some fields: id, name…. It will appear in a grid in the browser and the user can add/edit records. That’s why in save action I will give array with records where the new records id is a negative number for example:
array[0] = {"id" => "-1", "name" => "New record 1"}
array[1] = {"id" => "-2", "name" => "New record 2"}
array[2] = {"id" => "1", "name" => "Exist record 1"}
array[3] = {"id" => "2", "name" => "Exist record 2"}
In doctrine 1 I used this:
if (array[x]["id"] < 0) {
$record = new $MyRecord();
$record->fromArray(array[x]);
} else {
$record = Doctrine::getTable($MyRecord)->find(array[x]["id"]);
$record->merge(array[x]);
}
but how can I do this in D2?
In my code where I create/update I usually pass in the array, then loop over it assigning each member variable of the class. Or if there is something more specific I need to do, I just manually assign each value from the array to the class member variables. Doctrine 2 requires you to be much more explicit in the way you do some things. Here is an example method from a service class.
Here’s another example with the loop:
The second example with the loop will only work if you know your entity doesn’t have any references to other entities (like in the first example where page has a site).