0

I need to clone an entity called Projects with 2 entity relations calls Zone and Sector. I'd tried to use something like that in the controller:

$new_project = clone $project;
$em = $this->getDoctrine()->getManager();
$em->persist($new_project);
$em->flush();

It works for copy the entity Projects, but it doesn't copy the other 2 entities and its relations...

Any suggestion?

EDIT: I found a fast and easy solution in this question. Thanks!

Community
  • 1
  • 1
Angel
  • 357
  • 3
  • 6
  • 17

2 Answers2

1

What I did when I've run this issue is write a function which reads the object's metadata dynamically, iterates through them, and copy each field manually.

The metadata will have a property called "fieldNames" with the non-relational fields, and "associationMappings" with the relational ones. An example:

    $em = $this->getDoctrine()->getManager();
    $objectToClone = $em->getRepository('Xxx')->find(xx);
    $class = get_class($objectToClone);
    $metadata = $em->getMetadataFactory()->getMetadataFor($class);
    // Symfony\Component\PropertyAccess\PropertyAccessor;
    $accessor = new PropertyAccessor();
    $newObject = new Xxx();
    foreach ($metadata->getFieldNames() as $value) {
        if (property_exists($objectToClone, $value)) {
            $accessor->setValue($newObject, $value, $accessor->getValue($objectToClone, $value));
        }
    }
    foreach ($metadata->getAssociationMappings() as $key => $value) {
        if (property_exists($objectToClone, $key)) {
            $accessor->setValue($newObject, $key, $accessor->getValue($objectToClone, $key));
        }
    }

Hope this helps.

zeykzso
  • 493
  • 2
  • 9
0

Try this function:

public static function cloneObject( $source ) {
    if ( $source === null ) {
        return null;
    }

    return unserialize( serialize( $source ) );
}

I use it to clone entities in a zf2 project, and it works fine. It allows me to iterate through One to Many related entities from the main entity.

lluisaznar
  • 2,383
  • 1
  • 15
  • 14