Skip to content

Instantly share code, notes, and snippets.

@quentint
Last active August 29, 2015 13:59
Show Gist options
  • Save quentint/10834946 to your computer and use it in GitHub Desktop.
Save quentint/10834946 to your computer and use it in GitHub Desktop.
SonataAdminBundle sonata_type_collection entity relations
class Entity {
/**
* @var ArrayCollection
* @ORM\OneToMany(
* targetEntity="PlaceThemePresence",
* mappedBy="place",
* cascade={"persist"},
* orphanRemoval=true
* )
* @ORM\OrderBy({"id" = "ASC"})
*/
protected $placeThemePresences;
public function __construct() {
$this->placeThemePresences=new ArrayCollection();
}
/**
* @return ArrayCollection
*/
public function getPlaceThemePresences() {
return $this->placeThemePresences;
}
/**
* @param ArrayCollection $presences
*/
public function setPlaceThemePresences($presences) {
$this->placeThemePresences = new ArrayCollection();
foreach ($presences as $presence) {
$this->addPlaceThemePresence($presence);
}
}
public function addPlaceThemePresence(PlaceThemePresence $presence) {
if (!$this->getPlaceThemePresences()->contains($presence)) {
$this->getPlaceThemePresences()->add($presence);
$presence->setPlace($this);
}
return $this;
}
public function removePlaceThemePresence(PlaceThemePresence $presence) {
if ($this->getPlaceThemePresences()->contains($presence)) {
$this->getPlaceThemePresences()->removeElement($presence);
$presence->removePlace($this);
}
return $this;
}
public function updatePresences() {
$this->setPlaceThemePresences($this->getPlaceThemePresences());
}
}
protected function configureFormFields(FormMapper $formMapper)
{
// ...
$formMapper
->add('placeThemePresences', 'sonata_type_collection',
array('required'=>true, 'label'=>'Themes'),
array('edit' => 'inline','inline' => 'table')
)
->add('links', 'sonata_type_collection', array('required'=>false), array(
'edit' => 'inline',
'inline' => 'table'
))
;
// ...
}
// RELATION FIXES
public function prePersist($target) {
$target->updatePresences();
}
public function preUpdate($target) {
$target->updatePresences();
}
protected function configureFormFields(FormMapper $formMapper) {
$isChild=$this->hasParentFieldDescription() || $this->isChild();
$isThemeChild=false;
$isPlaceChild=false;
if ($isChild) {
$isThemeChild=$this->getParentFieldDescription()->getAdmin() instanceof ThemeAdmin;
$isPlaceChild=$this->getParentFieldDescription()->getAdmin() instanceof PlaceAdmin;
}
if (!$isPlaceChild) $formMapper->add('place');
if (!$isThemeChild) $formMapper->add('theme');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment