You are here

public function Table::formatText in YAML Form 8

Format an element's value as plain text.

Parameters

array $element: An element.

array|mixed $value: A value.

array $options: An array of options.

Return value

string The element's value formatted as plain text or a render array.

Overrides YamlFormElementBase::formatText

File

src/Plugin/YamlFormElement/Table.php, line 133

Class

Table
Provides a 'table' element.

Namespace

Drupal\yamlform\Plugin\YamlFormElement

Code

public function formatText(array &$element, $value, array $options = []) {

  // Render the HTML table.
  $build = $this
    ->formatHtml($element, $value, $options);
  $html = \Drupal::service('renderer')
    ->renderPlain($build);

  // Convert table in pipe delimited plain text.
  $html = preg_replace('#\\s*</td>\\s*<td[^>]*>\\s*#', ' | ', $html);
  $html = preg_replace('#\\s*</th>\\s*<th[^>]*>\\s*#', ' | ', $html);
  $html = preg_replace('#^\\s+#m', '', $html);
  $html = preg_replace('#\\s+$#m', '', $html);
  $html = preg_replace('#\\n+#s', "\n", $html);
  $html = strip_tags($html);

  // Remove blank links from text.
  // From: http://stackoverflow.com/questions/709669/how-do-i-remove-blank-lines-from-text-in-php
  $html = preg_replace("/(^[\r\n]*|[\r\n]+)[\\s\t]*[\r\n]+/", "\n", $html);

  // Add divider between (optional) header.
  if (!empty($element['#header'])) {
    $lines = explode("\n", trim($html));
    $lines[0] .= "\n" . str_repeat('-', Unicode::strlen($lines[0]));
    $html = implode("\n", $lines);
  }
  return $html;
}