FormStateValuesTrait.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Drupal\Core\Form;
  3. use Drupal\Component\Utility\NestedArray;
  4. /**
  5. * Provides methods to manage form state values.
  6. *
  7. * @see \Drupal\Core\Form\FormStateInterface
  8. *
  9. * @ingroup form_api
  10. */
  11. trait FormStateValuesTrait {
  12. /**
  13. * Implements \Drupal\Core\Form\FormStateInterface::getValues()
  14. */
  15. abstract public function &getValues();
  16. /**
  17. * Implements \Drupal\Core\Form\FormStateInterface::getValue()
  18. */
  19. public function &getValue($key, $default = NULL) {
  20. $exists = NULL;
  21. $value = &NestedArray::getValue($this->getValues(), (array) $key, $exists);
  22. if (!$exists) {
  23. $value = $default;
  24. }
  25. return $value;
  26. }
  27. /**
  28. * Implements \Drupal\Core\Form\FormStateInterface::setValues()
  29. */
  30. public function setValues(array $values) {
  31. $existing_values = &$this->getValues();
  32. $existing_values = $values;
  33. return $this;
  34. }
  35. /**
  36. * Implements \Drupal\Core\Form\FormStateInterface::setValue()
  37. */
  38. public function setValue($key, $value) {
  39. NestedArray::setValue($this->getValues(), (array) $key, $value, TRUE);
  40. return $this;
  41. }
  42. /**
  43. * Implements \Drupal\Core\Form\FormStateInterface::unsetValue()
  44. */
  45. public function unsetValue($key) {
  46. NestedArray::unsetValue($this->getValues(), (array) $key);
  47. return $this;
  48. }
  49. /**
  50. * Implements \Drupal\Core\Form\FormStateInterface::hasValue()
  51. */
  52. public function hasValue($key) {
  53. $exists = NULL;
  54. $value = NestedArray::getValue($this->getValues(), (array) $key, $exists);
  55. return $exists && isset($value);
  56. }
  57. /**
  58. * Implements \Drupal\Core\Form\FormStateInterface::isValueEmpty()
  59. */
  60. public function isValueEmpty($key) {
  61. $exists = NULL;
  62. $value = NestedArray::getValue($this->getValues(), (array) $key, $exists);
  63. return !$exists || empty($value);
  64. }
  65. /**
  66. * Implements \Drupal\Core\Form\FormStateInterface::setValueForElement()
  67. */
  68. public function setValueForElement(array $element, $value) {
  69. return $this->setValue($element['#parents'], $value);
  70. }
  71. }