Created
November 25, 2016 10:38
-
-
Save pzaj2/8f2676870349914ed96257dff712a512 to your computer and use it in GitHub Desktop.
readonly form field for entity
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 | |
namespace CustomBundle\Form; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\OptionsResolver\OptionsResolver; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\Form\Extension\Core\Type\CheckboxType; | |
class ExampleFormType extends AbstractType | |
{ | |
/** | |
* {@inheritdoc} | |
*/ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
$builder | |
->add('unmappedField', CheckboxType::class, [ | |
'attr' => [ | |
'disabled' => 'disabled', | |
'readonly' => 'readonly', | |
], | |
'mapped' => false, | |
]) | |
; | |
// other fields | |
$builder->get('unmappedField') | |
->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'setUnmappedField']) | |
->addEventListener(FormEvents::SUBMIT, [$this, 'setUnmappedField']); | |
} | |
public function setUnmappedField(FormEvent $event) | |
{ | |
$formField = $event->getForm(); | |
$entity = $formField->getParent()->getData(); | |
if($entity) { | |
$event->setData($entity->getUnmappedField()); | |
} | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function configureOptions(OptionsResolver $resolver) | |
{ | |
$resolver->setDefaults(array( | |
'data_class' => 'CustomBundle\Entity\ExampleEntity', | |
)); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getBlockPrefix() | |
{ | |
return 'custombundle_example'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment