Last active
November 1, 2018 11:35
-
-
Save ostrolucky/a6221f8e98916bf7bffac6347abd4da1 to your computer and use it in GitHub Desktop.
Convert Symfony Form to text values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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