selectfield.class.inc.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. namespace Combodo\iTop\Form\Field;
  19. use \Closure;
  20. use \Dict;
  21. use \Combodo\iTop\Form\Field\MultipleChoicesField;
  22. /**
  23. * Description of SelectField
  24. *
  25. * @author Guillaume Lajarige <guillaume.lajarige@combodo.com>
  26. */
  27. class SelectField extends MultipleChoicesField
  28. {
  29. const DEFAULT_NULL_CHOICE_LABEL = 'UI:SelectOne';
  30. const DEFAULT_STARTS_WITH_NULL_CHOICE = true;
  31. protected $bStartsWithNullChoice;
  32. public function __construct($sId, Closure $onFinalizeCallback = null)
  33. {
  34. parent::__construct($sId, $onFinalizeCallback);
  35. $this->bStartsWithNullChoice = static::DEFAULT_STARTS_WITH_NULL_CHOICE;
  36. }
  37. /**
  38. * Returns if the select starts with a dummy choice before its choices.
  39. * This can be useful when you want to force the user to explicitly select a choice.
  40. *
  41. * @return boolean
  42. */
  43. public function GetStartsWithNullChoice()
  44. {
  45. return $this->bStartsWithNullChoice;
  46. }
  47. public function SetStartsWithNullChoice($bStartsWithNullChoice)
  48. {
  49. $this->bStartsWithNullChoice = $bStartsWithNullChoice;
  50. return $this;
  51. }
  52. /**
  53. * Returns the field choices with null choice first
  54. *
  55. * @return array
  56. */
  57. public function GetChoices()
  58. {
  59. $aChoices = parent::GetChoices();
  60. if ($this->bStartsWithNullChoice && !array_key_exists(null, $aChoices))
  61. {
  62. $aChoices = array(null => Dict::S(static::DEFAULT_NULL_CHOICE_LABEL)) + $aChoices;
  63. }
  64. return $aChoices;
  65. }
  66. }