You are here

public function ApiMarkup::getFormMarkup in FormAssembly 8

Retrieve the HTML for a FormAssembly form.

The FA API recognizes query parameters passed on the rest URL and will use them to pre-fill fields in the returned form markup. Here we fold in parameters configured via formassembly_form() and expose the hook hook_formassembly_form_params_alter(&$params) to allow modules to modify the passed parameter list.

Parameters

\Drupal\formassembly\Entity\FormAssemblyEntity $entity: Entity form object.

Return value

string HTML representation of the form.

File

src/ApiMarkup.php, line 127

Class

ApiMarkup
Service class for FormAssembly API: Fetches form markup.

Namespace

Drupal\formassembly

Code

public function getFormMarkup(FormAssemblyEntity $entity) {
  $params = [];
  if (!$entity->query_params
    ->isEmpty()) {
    $params = $entity->query_params->value;
  }

  // Expose hook_formassembly_form_params_alter()
  $this->moduleHandler
    ->alter('formassembly_form_params', $params);

  // Replace any tokens found in the parameter pair values.
  $data = [
    'user' => $this->userProxy
      ->getAccount(),
  ];
  foreach ($this->routeMatch
    ->getParameters() as $parameter) {
    if ($parameter instanceof ContentEntityInterface) {
      $data[$parameter
        ->getEntityTypeId()] = $parameter;
    }
  }
  foreach ($params as $key => $value) {
    $params[$key] = $this->tokens
      ->replace($value, $data, [
      'clear' => TRUE,
    ]);
  }
  $params = array_filter($params, function ($value) {
    return !is_null($value) && $value !== '';
  });

  // Make FA rest call and return form markup.
  $url = $this
    ->getUrl('/rest/forms/view/' . $entity->faid->value);
  $url
    ->setOptions([
    'query' => $params,
  ]);
  $request = $this->httpClient
    ->get($url
    ->toString(TRUE)
    ->getGeneratedUrl());

  // Guzzle throws an Exception on http 400/500 errors.
  // Ensure we have a 200.
  if ($request
    ->getStatusCode() != 200) {
    throw new \UnexpectedValueException('Http return code 200 expected.  Code ' . $request
      ->getStatusCode() . ' received.');
  }
  return $request
    ->getBody()
    ->getContents();
}