LockExtension.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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\AbstractAdminExtension;
  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 AbstractAdminExtension
  21. {
  22. /**
  23. * @var string
  24. */
  25. protected $fieldName = '_lock_version';
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function configureFormFields(FormMapper $form)
  30. {
  31. $admin = $form->getAdmin();
  32. $formBuilder = $form->getFormBuilder();
  33. // PHP 5.3 BC
  34. $fieldName = $this->fieldName;
  35. $formBuilder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($admin, $fieldName) {
  36. $data = $event->getData();
  37. $form = $event->getForm();
  38. if (null === $data || $form->getParent()) {
  39. return;
  40. }
  41. $modelManager = $admin->getModelManager();
  42. if (!$modelManager instanceof LockInterface) {
  43. return;
  44. }
  45. if (null === $lockVersion = $modelManager->getLockVersion($data)) {
  46. return;
  47. }
  48. $form->add($fieldName, 'hidden', array(
  49. 'mapped' => false,
  50. 'data' => $lockVersion,
  51. ));
  52. });
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function preUpdate(AdminInterface $admin, $object)
  58. {
  59. if (!$admin->hasRequest() || !$data = $admin->getRequest()->get($admin->getUniqid())) {
  60. return;
  61. }
  62. if (!isset($data[$this->fieldName])) {
  63. return;
  64. }
  65. $modelManager = $admin->getModelManager();
  66. if (!$modelManager instanceof LockInterface) {
  67. return;
  68. }
  69. $modelManager->lock($object, $data[$this->fieldName]);
  70. }
  71. }