Created
March 21, 2018 06:27
-
-
Save covex-nn/1cb75d95b6805768a4a20eb673726782 to your computer and use it in GitHub Desktop.
MediaType as a child form type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Block; | |
use App\Entity\SonataMediaMedia; | |
use App\Traits\EntityManagerTrait; | |
use Sonata\AdminBundle\Form\FormMapper; | |
use Sonata\BlockBundle\Block\Service\AbstractAdminBlockService; | |
use Sonata\BlockBundle\Model\BlockInterface; | |
abstract class AbstractMediaUploaderBlock extends AbstractAdminBlockService | |
{ | |
use EntityManagerTrait; | |
protected $medias = []; | |
public function buildEditForm(FormMapper $formMapper, BlockInterface $block): void | |
{ | |
$this->loadMedias($block); | |
} | |
public function prePersist(BlockInterface $block): void | |
{ | |
parent::prePersist($block); | |
$this->saveMedias($block); | |
} | |
public function preUpdate(BlockInterface $block): void | |
{ | |
parent::preUpdate($block); | |
$this->saveMedias($block); | |
} | |
protected function loadMedias(BlockInterface $block): void | |
{ | |
$repository = $this->em->getRepository(SonataMediaMedia::class); | |
foreach ($this->medias as $name) { | |
$file = $block->getSetting($name); | |
if (null !== $file) { | |
if (is_numeric($file)) { | |
$file = $repository->find($file); | |
} | |
if (!$file instanceof SonataMediaMedia) { | |
$file = null; | |
} | |
$block->setSetting($name, $file); | |
} | |
} | |
} | |
protected function saveMedias(BlockInterface $block): void | |
{ | |
foreach ($this->medias as $name) { | |
$file = $block->getSetting($name); | |
if ($file instanceof SonataMediaMedia) { | |
if ($file->getSize()) { | |
$this->em->persist($file); | |
$this->em->flush(); | |
$block->setSetting($name, $file->getId()); | |
} | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Traits; | |
use Doctrine\ORM\EntityManagerInterface; | |
trait EntityManagerTrait | |
{ | |
/** | |
* @var EntityManagerInterface | |
*/ | |
protected $em; | |
/** | |
* @required | |
*/ | |
public function setEntityManager(EntityManagerInterface $em): void | |
{ | |
$this->em = $em; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment