saving_hooks.rst 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. Saving hooks
  2. ============
  3. When the model is persited upon on the object stated two Admin methods are always call. You can extends this
  4. method to add custom business logic.
  5. - new object : ``prePersist($object)`` / ``postPersist($object)``
  6. - new object : ``preUpdate($object)`` / ``postUpdate($object)``
  7. - deleted object : ``preRemove($object)`` / ``postRemove($object)``
  8. Example used with the FOS/UserBundle
  9. ------------------------------------
  10. The ``FOSUserBundle`` provides authentication features for your Symfony2 Project. Compatible with Doctrine ORM & ODM.
  11. See https://github.com/FriendsOfSymfony/UserBundle for more information.
  12. The user management system requires to perform specific call when the user password or username are updated. This
  13. is how the Admin bundle can be used to solve the issue by using the ``prePersist`` saving hook.
  14. .. code-block:: php
  15. <?php
  16. namespace FOS\UserBundle\Admin\Entity;
  17. use Sonata\AdminBundle\Admin\Admin;
  18. use FOS\UserBundle\Model\UserManagerInterface;
  19. class UserAdmin extends Admin
  20. {
  21. protected function configureFormFields(FormMapper $formMapper)
  22. {
  23. $formMapper
  24. ->with('General')
  25. ->add('username')
  26. ->add('email')
  27. ->add('plainPassword', 'text')
  28. ->end()
  29. ->with('Groups')
  30. ->add('groups', 'sonata_type_model', array('required' => false))
  31. ->end()
  32. ->with('Management')
  33. ->add('roles', 'sonata_security_roles', array( 'multiple' => true))
  34. ->add('locked', null, array('required' => false))
  35. ->add('expired', null, array('required' => false))
  36. ->add('enabled', null, array('required' => false))
  37. ->add('credentialsExpired', null, array('required' => false))
  38. ->end()
  39. ;
  40. }
  41. public function preUpdate($user)
  42. {
  43. $this->getUserManager()->updateCanonicalFields($user);
  44. $this->getUserManager()->updatePassword($user);
  45. }
  46. public function setUserManager(UserManagerInterface $userManager)
  47. {
  48. $this->userManager = $userManager;
  49. }
  50. /**
  51. * @return UserManagerInterface
  52. */
  53. public function getUserManager()
  54. {
  55. return $this->userManager;
  56. }
  57. }
  58. The service declaration where the ``UserManager`` is injected into the Admin class.
  59. .. code-block:: xml
  60. <service id="fos.user.admin.user" class="%fos.user.admin.user.class%">
  61. <tag name="sonata.admin" manager_type="orm" group="fos_user" />
  62. <argument />
  63. <argument>%fos.user.admin.user.entity%</argument>
  64. <argument />
  65. <call method="setUserManager">
  66. <argument type='service' id='fos_user.user_manager' />
  67. </call>
  68. </service>