<?php
namespace Cms\FileBundle\Form\Type;
use Cms\CoreBundle\Util\Doctrine\EntityManager;
use Cms\FileBundle\Controller\ModalController;
use Cms\FileBundle\Doctrine\Nodes\FileRepository;
use Cms\FileBundle\Entity\Nodes\File;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Class FileModalType
* @package Cms\FileBundle\Form\Type
*/
class FileModalType extends AbstractType
{
/**
* @var FileRepository
*/
protected $repFileRepository;
/**
* @param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->repFileRepository = $em->getRepository(File::class);
}
/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['mode'] = $options['modal_mode'];
$view->vars['host'] = $options['host'];
$view->vars['container'] = $options['container'];
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setRequired(array(
'container',
));
$resolver->setDefaults(array(
'modal_mode' => ModalController::MODES__ID,
'host' => null,
));
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
if ($options['modal_mode'] === ModalController::MODES__ID) {
$builder->addModelTransformer(
new CallbackTransformer(
function (File $original = null) {
if ( ! empty($original)) {
return $original->getId();
}
return null;
},
function ($submitted = null) {
if ( ! empty($submitted)) {
return $this->repFileRepository->findExact(intval($submitted));
}
return null;
}
)
);
}
}
/**
* {@inheritdoc}
* This should be treated as a hidden form type, as its display is rather complex and is handled specially.
*/
public function getParent(): ?string
{
return TextType::class;
}
}