You are here

public static function ScssFontFamily::processFontFamily in SCSS Compiler 1.0.x

Process the element before it gets rendered in the form.

Parameters

array $element: The element to process before being rendered.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

array $complete_form: The complete form.

Return value

array The resulting element after having been processed.

File

src/Element/ScssFontFamily.php, line 140

Class

ScssFontFamily
A form element to represent font families.

Namespace

Drupal\compiler_scss\Element

Code

public static function processFontFamily(array &$element, FormStateInterface $form_state, array &$complete_form) {

  // Create a unique ID for this element.
  $wrapper_id = implode('-', $element['#parents'] + [
    'add-more-wrapper',
  ]);
  $wrapper_id = Html::getUniqueId($wrapper_id);

  // Add the wrapper to the element so that it can be replaced via AJAX.
  $element['#prefix'] = '<div id="' . $wrapper_id . '">';
  $element['#suffix'] = '</div>';

  // Fetch the current value of the element.
  $value = self::getValue($element);

  // Check if the number of children for this element can be initialized based
  // on the current value of the element.
  if (!$form_state
    ->get($key = "{$element['#name']}_children")) {

    // If the value is an array, use its count as the initial value.
    $form_state
      ->set($key, is_array($value) ? count($value) : 0);
  }

  // Construct a child textfield for each delta in the element.
  for ($delta = 0; $delta < $form_state
    ->get($key); ++$delta) {
    $default = NULL;

    // Attempt to extract the current value for this textfield delta.
    if (is_array($value) && array_key_exists($delta, $value)) {
      $default = $value[$delta];
    }

    // Create the textfield for this delta in the element.
    $element[$delta] = [
      '#type' => 'textfield',
      '#name' => "{$element['#name']}[{$delta}]",
      '#maxlength' => $element['#maxlength'],
      '#size' => $element['#size'],
      '#title' => $element['#title'],
      '#title_display' => 'none',
      '#default_value' => $default,
    ];

    // Add the textfield to the array of children for this element.
    $element['#children'][$delta] =& $element[$delta];
  }

  // Create an "Add another item" button to add more textfields via AJAX.
  $element['add_more'] = [
    '#type' => 'submit',
    '#name' => "{$element['#name']}[add_more]",
    '#value' => t('Add another item'),
    '#limit_validation_errors' => [
      [
        $element['#name'],
      ],
    ],
    '#submit' => [
      [
        get_class(),
        'addMoreSubmit',
      ],
    ],
    '#ajax' => [
      'callback' => [
        get_class(),
        'addMoreAjax',
      ],
      'wrapper' => $wrapper_id,
      'effect' => 'fade',
    ],
  ];

  // Add the button to the array of children for this element.
  $element['#children']['add_more'] =& $element['add_more'];
  return $element;
}