saving_hooks.rst 2.9 KB

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