Skip to content

Instantly share code, notes, and snippets.

@ostrolucky
Last active November 1, 2018 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ostrolucky/a6221f8e98916bf7bffac6347abd4da1 to your computer and use it in GitHub Desktop.
Save ostrolucky/a6221f8e98916bf7bffac6347abd4da1 to your computer and use it in GitHub Desktop.
Convert Symfony Form to text values
<?php
class SymfonyFormTransformer {
/**
* @param FormInterface $form
* @return string
*/
public function transformFormToText(FormInterface $form)
{
$txt = '';
foreach ($form->getData() as $inputName => $inputValue) {
$formElement = $form->get($inputName);
if (!$formElement) {
continue;
}
$formElementConfig = $formElement->getConfig();
$formElementLabel = $formElementConfig->getOption('label');
if (!$formElementConfig->hasOption('choices')) {
$txt = $this->appendValue($txt, $formElementLabel, $inputValue);
continue;
}
$formElementChoices = $formElementConfig->getOption('choices');
$formElementChoices = is_bool(reset($formElementChoices)) ?: array_flip($formElementChoices);
if (!is_array($inputValue)) {
$choice = is_bool($inputValue) ?: $formElementChoices[$inputValue];
$txt = $this->appendValue(
$txt,
$formElementLabel,
(is_bool($choice) ? ($choice ? 'Yes' : 'No') : $choice)
);
continue;
}
foreach ($inputValue as $selectedChoice) {
$txt = $this->appendValue($txt, $formElementLabel, $formElementChoices[$selectedChoice]);
}
}
return $txt;
}
/**
* @param string $txt
* @param string $label
* @param string $value
* @return string
*/
private function appendValue($txt, $label, $value)
{
return $txt.$label.': "'.$value."\"\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment