You are here

public function Populate::populateForm in Prepopulate 8.2

Populate form with values.

Parameters

array &$form: The form or form element to populate.

null|array|string $request_slice: (optional) The values to populate.

Return value

array The populated form.

Overrides PopulateInterface::populateForm

File

src/Populate.php, line 90

Class

Populate
Service to populate fields from URL.

Namespace

Drupal\prepopulate

Code

public function populateForm(array &$form, $request_slice = NULL) {
  if (is_null($request_slice)) {
    $request_slice = $this->request
      ->getCurrentRequest()->query
      ->get('edit');
  }
  if (is_array($request_slice)) {
    foreach (array_keys($request_slice) as $request_variable) {
      if (isset($form[$request_variable])) {
        $element =& $form[$request_variable];
        if (isset($element['widget'][0]['value']['#type'])) {
          $type = $element['widget'][0]['value']['#type'];
        }
        elseif (isset($element['widget'][0]['target_id']['#type'])) {
          $type = $element['widget'][0]['target_id']['#type'];
        }
        elseif (isset($element['widget']['#type'])) {
          $type = $element['widget']['#type'];
        }
        elseif (isset($element['#type'])) {
          $type = $element['#type'];
        }
        if (Element::child($request_variable) && !empty($element) && (empty($type) || in_array($type, $this->whitelistedTypes))) {
          $this
            ->populateForm($element, $request_slice[$request_variable]);
        }
      }
    }
  }
  else {

    // If we don't have a form type, we cannot do anything.
    if (empty($form['#type'])) {
      return;
    }

    // If we already have a value in the form, don't overwrite it.
    if (!empty($form['#value']) && is_scalar($form['#value'])) {
      return;
    }

    // If we don't have access, don't alter it.
    if (isset($form['#access']) && $form['#access'] === FALSE) {
      return;
    }
    $value = Html::escape($request_slice);
    switch ($form['#type']) {
      case 'entity_autocomplete':
        $form['#value'] = $this
          ->formatEntityAutocomplete($value, $form);
        break;
      case 'checkbox':
        $form['#checked'] = $value === 'true';
      default:
        $form['#value'] = $value;
        break;
    }
  }
}