26

In $entity variable, there is an object of same type as $other_address, but with all field values filled in.

I want to set all fields in $other_address object to have exact same values as $entity object.

Is this doable in less then N number of lines, where N is number of fields I need to set?

I tried "clone" keyword, but it didnt work.

Here's the code.

                $other_address = $em->getRepository('PennyHomeBundle:Address')
          ->findBy(array('user' => $this->get('security.context')->getToken()->getUser()->getId(), 'type' => $check_type));
                $other_address = $other_address[0];


                //I want to set all values in this object to have values from another object of same type
                $other_address->setName($entity->getName());
                $other_address->setAddress1($entity->getAddress1());
                $other_address->setAddress2($entity->getAddress2());
                $other_address->setSuburbTown($entity->getSuburbTown());
                $other_address->setCityState($entity->getCityState());
                $other_address->setPostZipCode($entity->getPostZipCode());
                $other_address->setPhone($entity->getPhone());
                $other_address->setType($check_type);
Tool
  • 12,126
  • 15
  • 70
  • 120

3 Answers3

40

I'm not sure why cloning won't work.

This seems to work for me, at least in a basic test case:

$A = $em->find('Some\Entity',1);

$B = clone $A;
$B->setId(null);

If you've got relationships to worry about, you might want to safely implement __clone so it does what you want it to do with related entities.

marcv
  • 1,874
  • 4
  • 24
  • 45
timdev
  • 61,857
  • 6
  • 82
  • 92
  • 5
    As DavidLin points, you don't have to "unset" the entity ID (if the field is properly marked as ID) – Sergi Aug 08 '13 at 11:33
  • HI @timdev, what if i wanted to copy, assume i have a temp object and i need to merge that it in original object? is that possible? – senK Dec 24 '14 at 09:59
29

Just Clone the entity, you don't even need to unset the id. Doctrine has tackled this for you

David Lin
  • 13,168
  • 5
  • 46
  • 46
  • 4
    It seems that if you use your own ID generators the ID isn't set to null. Even if the ID field is marked as being an ID. – flu Apr 09 '14 at 07:54
1
$A = $em->find('Some\Entity',1);

$B = clone $A;
$em->persist($B);
$em->flush();

if you merge it will update the entity, best you use persist() it will duplicate the entire row and add auto incremented primary key

Waqar Haider
  • 929
  • 10
  • 33