I tried to save my pdf files into the file system of sonata media bundle and insert the correct database entry.
I created my file with dompdf as following:
$dompdf = new Dompdf($pdfOptions);
$html = $this->renderView("pdf/hrprotokoll.html.twig", [
'result' => $result,
'vals' => $vals,
'title' => 'Prüfprotokoll',
'item' => $item,
]);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$output = $dompdf->output();
$publicDirectory = $request->server->get('DOCUMENT_ROOT') . '/uploads/hrprotokolle/'.$this->getUser()->getStandort()->getId();
$pdfFilepath = $publicDirectory . '/'. time().'.pdf';
$file = time().'.pdf';
file_put_contents($pdfFilepath, $output);
ok, now the file is saved correctly without errors. The question now is how to manage this file with Sonata MediaBundle. Ive tried the following:
$mediaManager = new MediaManager();
$media = new Media();
$media->setBinaryContent($file);
$media->setContext('default');
$media->setProviderName('sonata.media.provider.file');
$mediaManager->save($media);
Error:
Too few arguments to function Sonata\Doctrine\Model\BaseManager::__construct(), 0 passed... ($mediaManager)
Im not able to set the correct way. Anyone have an idea to solve this problem? Thx
The problem was: $mediaManager (service sonata.media.manager.media) cant autowire so you have to do this manually.
at first check this service in your terminal and find informations about this service by typing the following:
php bin/console debug:container sonata.media.manager.media
The Result is:
Service ID sonata.media.manager.media
Class Sonata\MediaBundle\Entity\MediaManager
Ok, now go to your services.yaml and create the alias:
Sonata\MediaBundle\Entity\MediaManager: '@sonata.media.manager.media'
Its done. Now you can inject the MediaManager and it works for me:
use Sonata\MediaBundle\Entity\MediaManager;
private $mediaManager;
public function __construct(MediaManager $mediaManager)
{
$this->mediaManager = $mediaManager;
}
$media = new Media();
$this->mediaManager->save($media);