BaseGroupedMapper.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /*
  3. * This file is part of the Sonata 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. */
  11. namespace Sonata\AdminBundle\Mapper;
  12. /**
  13. * This class is used to simulate the Form API
  14. *
  15. */
  16. abstract class BaseGroupedMapper extends BaseMapper
  17. {
  18. protected $currentGroup;
  19. protected abstract function getGroups();
  20. protected abstract function setGroups(array $groups);
  21. /**
  22. * @param string $name
  23. * @param array $options
  24. *
  25. * @return \Sonata\AdminBundle\Mapper\BaseGroupedMapper
  26. */
  27. public function with($name, array $options = array())
  28. {
  29. $groups = $this->getGroups();
  30. if (!isset($groups[$name])) {
  31. $groups[$name] = array();
  32. }
  33. $groups[$name] = array_merge(array(
  34. 'collapsed' => false,
  35. 'fields' => array(),
  36. 'description' => false,
  37. 'translation_domain' => null,
  38. ), $groups[$name], $options);
  39. $this->setGroups($groups);
  40. $this->currentGroup = $name;
  41. return $this;
  42. }
  43. /**
  44. * @return \Sonata\AdminBundle\Mapper\BaseGroupedMapper
  45. */
  46. public function end()
  47. {
  48. $this->currentGroup = null;
  49. return $this;
  50. }
  51. /**
  52. * Add the fieldname to the current group
  53. *
  54. * @param string $fieldName
  55. */
  56. protected function addFieldToCurrentGroup($fieldName)
  57. {
  58. //Note this line must happen before the next line.
  59. //See https://github.com/sonata-project/SonataAdminBundle/pull/1351
  60. $currentGroup = $this->getCurrentGroupName();
  61. $groups = $this->getGroups();
  62. $groups[$currentGroup]['fields'][$fieldName] = $fieldName;
  63. $this->setGroups($groups);
  64. return $groups[$currentGroup];
  65. }
  66. /**
  67. * Return the name of the currently selected group. The method also makes
  68. * sure a valid group name is currently selected
  69. *
  70. * Note that this can have the side effect to change the "group" value
  71. * returned by the getGroup function
  72. *
  73. * @return string
  74. */
  75. protected function getCurrentGroupName()
  76. {
  77. if (!$this->currentGroup) {
  78. $this->with($this->admin->getLabel());
  79. }
  80. return $this->currentGroup;
  81. }
  82. }