BaseGroupedMapper.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. abstract protected function getGroups();
  20. abstract protected 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. 'class' => false,
  36. 'fields' => array(),
  37. 'description' => false,
  38. 'translation_domain' => null,
  39. ), $groups[$name], $options);
  40. $this->setGroups($groups);
  41. $this->currentGroup = $name;
  42. return $this;
  43. }
  44. /**
  45. * @return \Sonata\AdminBundle\Mapper\BaseGroupedMapper
  46. */
  47. public function end()
  48. {
  49. $this->currentGroup = null;
  50. return $this;
  51. }
  52. /**
  53. * Add the fieldname to the current group
  54. *
  55. * @param string $fieldName
  56. */
  57. protected function addFieldToCurrentGroup($fieldName)
  58. {
  59. // Note this line must happen before the next line.
  60. // See https://github.com/sonata-project/SonataAdminBundle/pull/1351
  61. $currentGroup = $this->getCurrentGroupName();
  62. $groups = $this->getGroups();
  63. $groups[$currentGroup]['fields'][$fieldName] = $fieldName;
  64. $this->setGroups($groups);
  65. return $groups[$currentGroup];
  66. }
  67. /**
  68. * Return the name of the currently selected group. The method also makes
  69. * sure a valid group name is currently selected
  70. *
  71. * Note that this can have the side effect to change the "group" value
  72. * returned by the getGroup function
  73. *
  74. * @return string
  75. */
  76. protected function getCurrentGroupName()
  77. {
  78. if (!$this->currentGroup) {
  79. $this->with($this->admin->getLabel());
  80. }
  81. return $this->currentGroup;
  82. }
  83. }