Posts

Showing posts from 2015

Symfony 2 How to keep cloned entity properties unchanged on change of main entity.

Often while we clone an entity, we find the property of new cloned entity gets changed based on changes to the main entity. Mostly when the change occurs on $form->handleRequest($request); Below magic function restricts the properties to keep their value unchanged by cloning deeper state of relationships. Code Example : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?php /** * clone */ public function __clone () { if ( $this -> id ) { // Remove orm reference to DB. $this -> id = null ; // Collect books to clone so that any further change to books in // main entity won't affect the cloned entity. $this -> books = clone $this -> books ; } } ?>

Filtering and Sorting a Doctrine Arraycollection

ArrayCollection object has so many useful in-build methods, that makes ArrayCollection superior comparable to normal PHP array. This post is about how to filter and sort an ArrayCollection so output of elements can be in certain order or filtered. Filter To filter we can use ArrayColleciton in-build filter method , which takes a predicate and returns all the elements satisfied by the predicate provided, keeping the order of the elements intact. A code example would be nice. Code Example : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?php /** * @var \Doctrine\Common\Collections\Collection */ $locations ; // ArrayCollection() variable that has $location object in its element. // To filter active locations. $activeLocations = $locations -> filter ( function ( $location ) { return $location -> getStatus (); // filter based on status. }); // Now $activeLocations holds all locaitons from $locations those have an active locaiton. ?> Sort Arra...