How to restrict modification to selected properties of an entity while persisting?
Let’s suppose we have an entity class and a generic FormType corresponding to the entity
class Entry {
protected $start_time;
protected $end_time;
protected $confirmed; // Boolean
// ... Other fields and getters and setters
}
On the CRUD of this entity, you might not want to allow any modification on start_time
or end_time
if the entity has been confirmed or in the above case when $confirmed === true
Here are couple of ways this can be solved:
-
Using the
EntityManager
you can retrieve original data of the entity.$em->getUnitOfWork()->getOriginalEntityData($entity)
returns an array with old data of an entity which can be used to reset the data.if($form->isSubmitted() && $editForm->isValid()) { // The form was submitted if($confirmed === true) { // if the entity was confirmed previously $oldData = $em->getUnitOfWork()->getOriginalEntityData($entity); $entity->setStartTime($oldData['start_time']); $entity->setEndTime($oldData['end_time']); } // After this you can happily persist the data $em->persist($entity); $em->flush(); }
-
Using Form Events
The following is a Symfony 3 Solution, try this solution for Symfony 2.
class EntityType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { // .... // .... // Your form fields $builder->addEventListener(FormEvents::POST_SET_DATA, array($this, 'onPreSetData')); } public function onPreSetData(FormEvent $event) { /** @var YourEntity $entity */ $entity = $event->getData(); $form = $event->getForm(); if($entity instanceof YourEntity) { if ($entity->getTimesheetEntry()->getTimeApproved() === true) { $config = $form->get('start_time')->getConfig(); $options = $config->getOptions(); $options['disabled'] = true; $form->add('start_time', get_class($config->getType()->getInnerType()), $options); $config = $form->get('end_time')->getConfig(); $options = $config->getOptions(); $options['disabled'] = true; $form->add('end_time', get_class($config->getType()->getInnerType()), $options); } } } }