Select.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * Form Element Select Data Model
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\Customer\Model\Metadata\Form;
  9. use Magento\Customer\Model\Metadata\ElementFactory;
  10. use Magento\Framework\App\RequestInterface;
  11. class Select extends AbstractData
  12. {
  13. /**
  14. * {@inheritdoc}
  15. */
  16. public function extractValue(RequestInterface $request)
  17. {
  18. return $this->_getRequestValue($request);
  19. }
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function validateValue($value)
  24. {
  25. $errors = [];
  26. $attribute = $this->getAttribute();
  27. $label = __($attribute->getStoreLabel());
  28. if ($value === false) {
  29. // try to load original value and validate it
  30. $value = $this->_value;
  31. }
  32. if ($attribute->isRequired() && empty($value) && $value !== '0') {
  33. $errors[] = __('"%1" is a required value.', $label);
  34. }
  35. if (!$errors && !$attribute->isRequired() && empty($value)) {
  36. return true;
  37. }
  38. if (count($errors) == 0) {
  39. return true;
  40. }
  41. return $errors;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function compactValue($value)
  47. {
  48. return $value;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function restoreValue($value)
  54. {
  55. return $this->compactValue($value);
  56. }
  57. /**
  58. * Return a text for option value
  59. *
  60. * @param string|int $value
  61. * @return string
  62. */
  63. protected function _getOptionText($value)
  64. {
  65. foreach ($this->getAttribute()->getOptions() as $option) {
  66. if ($option->getValue() == $value && !is_bool($value)) {
  67. return $option->getLabel();
  68. }
  69. }
  70. return '';
  71. }
  72. /**
  73. * Return formatted attribute value from entity model
  74. *
  75. * @param string $format
  76. * @return string
  77. */
  78. public function outputValue($format = ElementFactory::OUTPUT_FORMAT_TEXT)
  79. {
  80. $value = $this->_value;
  81. if ($format === ElementFactory::OUTPUT_FORMAT_JSON) {
  82. $output = $value;
  83. } elseif ($value != '') {
  84. $output = $this->_getOptionText($value);
  85. } else {
  86. $output = '';
  87. }
  88. return $output;
  89. }
  90. }