1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- <?php
- /*
- * This file is part of the Sonata Project package.
- *
- * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
- namespace Sonata\AdminBundle\Admin\Extension;
- use Sonata\AdminBundle\Admin\AbstractAdminExtension;
- use Sonata\AdminBundle\Admin\AdminInterface;
- use Sonata\AdminBundle\Form\FormMapper;
- use Sonata\AdminBundle\Model\LockInterface;
- use Symfony\Component\Form\FormEvent;
- use Symfony\Component\Form\FormEvents;
- /**
- * @author Emmanuel Vella <vella.emmanuel@gmail.com>
- */
- class LockExtension extends AbstractAdminExtension
- {
- /**
- * @var string
- */
- protected $fieldName = '_lock_version';
- /**
- * {@inheritdoc}
- */
- public function configureFormFields(FormMapper $form)
- {
- $admin = $form->getAdmin();
- $formBuilder = $form->getFormBuilder();
- // PHP 5.3 BC
- $fieldName = $this->fieldName;
- $formBuilder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($admin, $fieldName) {
- $data = $event->getData();
- $form = $event->getForm();
- if (null === $data || $form->getParent()) {
- return;
- }
- $modelManager = $admin->getModelManager();
- if (!$modelManager instanceof LockInterface) {
- return;
- }
- if (null === $lockVersion = $modelManager->getLockVersion($data)) {
- return;
- }
- $form->add(
- $fieldName,
- // NEXT_MAJOR: remove the check and add the FQCN
- method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix')
- ? 'Symfony\Component\Form\Extension\Core\Type\HiddenType'
- : 'hidden',
- array(
- 'mapped' => false,
- 'data' => $lockVersion,
- )
- );
- });
- }
- /**
- * {@inheritdoc}
- */
- public function preUpdate(AdminInterface $admin, $object)
- {
- if (!$admin->hasRequest() || !$data = $admin->getRequest()->get($admin->getUniqid())) {
- return;
- }
- if (!isset($data[$this->fieldName])) {
- return;
- }
- $modelManager = $admin->getModelManager();
- if (!$modelManager instanceof LockInterface) {
- return;
- }
- $modelManager->lock($object, $data[$this->fieldName]);
- }
- }
|