selectfield.class.inc.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 \Combodo\iTop\Form\Field\MultipleChoicesField;
  21. /**
  22. * Description of SelectField
  23. *
  24. * @author Guillaume Lajarige <guillaume.lajarige@combodo.com>
  25. */
  26. class SelectField extends MultipleChoicesField
  27. {
  28. const DEFAULT_NULL_CHOICE_LABEL = 'TOTR: - Choisir une valeur -';
  29. const DEFAULT_STARTS_WITH_NULL_CHOICE = true;
  30. protected $bStartsWithNullChoice;
  31. public function __construct($sId, Closure $onFinalizeCallback = null)
  32. {
  33. parent::__construct($sId, $onFinalizeCallback);
  34. $this->bStartsWithNullChoice = static::DEFAULT_STARTS_WITH_NULL_CHOICE;
  35. }
  36. /**
  37. * Returns if the select starts with a dummy choice before its choices.
  38. * This can be useful when you want to force the user to explicitly select a choice.
  39. *
  40. * @return boolean
  41. */
  42. public function GetStartsWithNullChoice()
  43. {
  44. return $this->bStartsWithNullChoice;
  45. }
  46. public function SetStartsWithNullChoice($bStartsWithNullChoice)
  47. {
  48. $this->bStartsWithNullChoice = $bStartsWithNullChoice;
  49. if (!array_key_exists(null, $this->aChoices))
  50. {
  51. $this->aChoices = array(null => static::DEFAULT_NULL_CHOICE_LABEL) + $this->aChoices;
  52. }
  53. return $this;
  54. }
  55. /**
  56. * Sets the choices for the fields
  57. * Overloads the methods for the super class in order to put a dummy choice first if necessary.
  58. *
  59. * @param array $aChoices
  60. * @return \Combodo\iTop\Form\Field\SelectField
  61. */
  62. public function SetChoices($aChoices)
  63. {
  64. if ($this->bStartsWithNullChoice && !array_key_exists(null, $aChoices))
  65. {
  66. $aChoices = array(null => static::DEFAULT_NULL_CHOICE_LABEL) + $aChoices;
  67. }
  68. parent::SetChoices($aChoices);
  69. return $this;
  70. }
  71. }