LockExtension.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Admin\Extension;
  11. use Sonata\AdminBundle\Admin\AdminExtension;
  12. use Sonata\AdminBundle\Admin\AdminInterface;
  13. use Sonata\AdminBundle\Form\FormMapper;
  14. use Sonata\AdminBundle\Model\LockInterface;
  15. use Symfony\Component\Form\FormEvent;
  16. use Symfony\Component\Form\FormEvents;
  17. /**
  18. * @author Emmanuel Vella <vella.emmanuel@gmail.com>
  19. */
  20. class LockExtension extends AdminExtension
  21. {
  22. protected $fieldName = '_lock_version';
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function configureFormFields(FormMapper $form)
  27. {
  28. $admin = $form->getAdmin();
  29. $formBuilder = $form->getFormBuilder();
  30. // PHP 5.3 BC
  31. $fieldName = $this->fieldName;
  32. $formBuilder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($admin, $fieldName) {
  33. $data = $event->getData();
  34. $form = $event->getForm();
  35. if (null === $data || $form->getParent()) {
  36. return;
  37. }
  38. $modelManager = $admin->getModelManager();
  39. if (!$modelManager instanceof LockInterface) {
  40. return;
  41. }
  42. if (null === $lockVersion = $modelManager->getLockVersion($data)) {
  43. return;
  44. }
  45. $form->add($fieldName, 'hidden', array(
  46. 'mapped' => false,
  47. 'data' => $lockVersion,
  48. ));
  49. });
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function preUpdate(AdminInterface $admin, $object)
  55. {
  56. if (!$admin->hasRequest() || !$data = $admin->getRequest()->get($admin->getUniqid())) {
  57. return;
  58. }
  59. if (!isset($data[$this->fieldName])) {
  60. return;
  61. }
  62. $modelManager = $admin->getModelManager();
  63. if (!$modelManager instanceof LockInterface) {
  64. return;
  65. }
  66. $modelManager->lock($object, $data[$this->fieldName]);
  67. }
  68. }