FormHelper.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Drupal\Core\Form;
  3. use Drupal\Core\Render\Element;
  4. /**
  5. * Provides helpers to operate on forms.
  6. *
  7. * @ingroup form_api
  8. */
  9. class FormHelper {
  10. /**
  11. * Rewrite #states selectors.
  12. *
  13. * @param array $elements
  14. * A renderable array element having a #states property.
  15. * @param string $search
  16. * A partial or entire jQuery selector string to replace in #states.
  17. * @param string $replace
  18. * The string to replace all instances of $search with.
  19. *
  20. * @see drupal_process_states()
  21. */
  22. public static function rewriteStatesSelector(array &$elements, $search, $replace) {
  23. if (!empty($elements['#states'])) {
  24. foreach ($elements['#states'] as $state => $ids) {
  25. static::processStatesArray($elements['#states'][$state], $search, $replace);
  26. }
  27. }
  28. foreach (Element::children($elements) as $key) {
  29. static::rewriteStatesSelector($elements[$key], $search, $replace);
  30. }
  31. }
  32. /**
  33. * Helper function for self::rewriteStatesSelector().
  34. *
  35. * @param array $conditions
  36. * States conditions array.
  37. * @param string $search
  38. * A partial or entire jQuery selector string to replace in #states.
  39. * @param string $replace
  40. * The string to replace all instances of $search with.
  41. */
  42. protected static function processStatesArray(array &$conditions, $search, $replace) {
  43. // Retrieve the keys to make it easy to rename a key without changing the
  44. // order of an array.
  45. $keys = array_keys($conditions);
  46. $update_keys = FALSE;
  47. foreach ($conditions as $id => $values) {
  48. if (strpos($id, $search) !== FALSE) {
  49. $update_keys = TRUE;
  50. $new_id = str_replace($search, $replace, $id);
  51. // Replace the key and keep the array in the same order.
  52. $index = array_search($id, $keys, TRUE);
  53. $keys[$index] = $new_id;
  54. }
  55. elseif (is_array($values)) {
  56. static::processStatesArray($conditions[$id], $search, $replace);
  57. }
  58. }
  59. // Updates the states conditions keys if necessary.
  60. if ($update_keys) {
  61. $conditions = array_combine($keys, array_values($conditions));
  62. }
  63. }
  64. }