I'm working on a Symfony 2.3 form which require that a field be only available on "create new" mode.
The field is a link in a Many-to-One relationship, i've managed to change the dropdown list by using a jQuery AutoComplete for ease of use via a FormEvents::PRE_SET_DATA
event ,however the FormEvents::PRE_SUBMIT
which is to turn the ID supplied into an object require a Doctrine ObjectManager.
This turn to be an Interface and throw the 'Cannot instantiate interface Doctrine\Common\Persistence\ObjectManager' .
I've looked at the following similar questions and documentations (Form Events , Form Events Dropdown, Doctrine Data Transformer, Dynamic Form Modification) but being so close to the end(And a newbie to both php and symfony) i wish no to re-write this piece.
May you find below my Event Listener and Data Transformer classes:
namespace XXXXXXXBundle\Form\EventListener;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use XXXXXXXXXXXXXBundle\Form\DataTransformer\rneToEcoleTransformer;
class AddFieldSubscriber implements EventSubscriberInterface {
private $manager;
public static function getSubscribedEvents() {
// Tells the dispatcher that you want to listen on the form.pre_set_data
// event and that the preSetData method should be called.
return array(\Symfony\Component\Form\FormEvents::PRE_SET_DATA => 'preSetData',
\Symfony\Component\Form\FormEvents::PRE_SUBMIT => 'preSubmit');
}
public function preSetData(\Symfony\Component\Form\FormEvent $event) {
$parents = $event->getData();
$form = $event->getForm();
//Verifie si le parent d'eleve est un nouveau
//ou s'il s'agit d' une mise à jour
if (!$parents || null === $parents->getId()) {
$form->add('ecole', 'text', array('invalid_message' => 'Ce RNE n\'est pas valide',
'attr' => array('data-id' => 'ecoles',
'data-url' => 'parents_json_ecoles'
)
)
);
}
}
public function preSubmit(\Symfony\Component\Form\FormEvent $event) {
$this->manager = new \Doctrine\Common\Persistence\ObjectManager;
$parents = $event->getData();
if (empty($parents['ecole'])) {
return;
}
$event->getForm()->get('ecole')->getConfig()->addModelTransformer(new rneToEcoleTransformer($this->manager));
}}
namespace XXXXXXXBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class rneToEcoleTransformer implements DataTransformerInterface {
private $manager;
public function __construct(\Doctrine\Common\Persistence\ObjectManager $manager) {
$this->manager = $manager;
}
public function transform($ecole) {
if (null === $ecole) {
return '';
}
return $ecole->getRne();
}
public function reverseTransform($rneNumber) {
if (!$rneNumber) {
return;
}
$ecole = $this->manager
->getRepository('XXXXXXXBundle:Ecole')
->find($rneNumber);
if (null === $ecole) {
throw new TransformationFailedException(sprintf(
'No matching data was found "%s" !', $rneNumber
));
}
return $ecole;
}}
Here is the action used :
private function createCreateForm(Parents $entity) {
$manager = $this->getDoctrine()->getManager();
$form = $this->createForm(new ParentsType($manager), $entity, array(
'action' => $this->generateUrl('parents_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Add'));
return $form;
}
The Formtype :
class XXXXType extends AbstractType {
private $manager;
public function __construct(\Doctrine\Common\Persistence\ObjectManager $manager) {
$this->manager = $manager;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('nom', 'text', array('label' => 'Nom *',
'attr' => array('placeholder' => 'Nom ',
'maxlength' => 250,
'trim' => true)
)
)
->add('prenoms', 'text', array('label' => 'Prénom(s) *',
'attr' => array('placeholder' => 'Prénom(s)',
'maxlength' => 250,
'trim' => true)
)
)
->add('date_de_naiss', 'date', array('widget' => 'single_text', 'format' => 'dd-MM-yyyy',
'label' => 'Date de naissance ',
'required' => false, 'data' => null,
'attr' => array('name' => 'datepicker')
)
)
->add('telephone', 'text', array('label' => 'Telephone *',
'attr' => array('placeholder' => '123-456-7890 or 1234567890')
)
)
->add('email', 'email', array('attr' => array('placeholder' => 'xxxx@xxxx.com',),
'trim' => true,
'required' => false,
'data' => null
)
);
$builder->addEventSubscriber(new AddFieldSubscriber($manager));
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'XXXXXXBundle\Entity\Parents'
));
}
/**
* @return string
*/
public function getName() {
return 'XXXXXXXXXsbundle_parents';
}
}