2

With Symfony2, I need to save an entity before use $form->bind() to compare the old and new one before flush.

I tried some functions :

$command = $repository->findCommandProductsByCommand( $id );
$old_command = clone $command;
// OR $old_command = $command;
$form = $this->createForm(new EditCommandType(), $command);

if( $request->getMethod() == 'POST' )
{
    $form->bind($request);
    if ( $form->isValid() )
    {

And I tried to save a little part of the entity like this :

$old_command = $command->getCommandProducts();

But when i try to access to the data of $old_command with one of these methods, i only get access to the newer value of the object from the form and not the older one.

$form->bind($request) is the main problem, but i didn't find a documentation which describes what exacly does bind().

Best regards

Solution for my case (thanks to zizoujab)

$command_entries = new ArrayCollection();
foreach ($command->getCommandproducts() as $entry) {
    $command_entries[] = clone $entry;
}

Now my ArrayCollection $command_entries isn't link to the previous entity.

  • bind() takes the submitted data and sets those values to their respective setters on your entity if you pass an entity. Are you trying to compare old data to new data? For example make sure that a password change is not using the same password as before? – Chase Jun 04 '13 at 20:22

1 Answers1

3

From clone manual :

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's
properties. Any properties that are references to other variables, will remain references.

I am assuming that getCommandProducts() returns an ArrayCollection so you will always get the new list.

you have to clone the list's elements too .

here is a full explanation and a sample of the solution : Symfony2/Doctrine: How to re-save an entity with a OneToMany as a cascading new row

Community
  • 1
  • 1
zizoujab
  • 7,603
  • 8
  • 41
  • 72