4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Form\Extension\Core\DataTransformer
;
14 use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
;
15 use Symfony\Component\Form\DataTransformerInterface
;
16 use Symfony\Component\Form\Exception\TransformationFailedException
;
19 * @author Bernhard Schussek <bschussek@gmail.com>
21 class ChoiceToBooleanArrayTransformer
implements DataTransformerInterface
25 private $placeholderPresent;
30 * @param ChoiceListInterface $choiceList
31 * @param Boolean $placeholderPresent
33 public function __construct(ChoiceListInterface
$choiceList, $placeholderPresent)
35 $this->choiceList
= $choiceList;
36 $this->placeholderPresent
= $placeholderPresent;
40 * Transforms a single choice to a format appropriate for the nested
41 * checkboxes/radio buttons.
43 * The result is an array with the options as keys and true/false as values,
44 * depending on whether a given option is selected. If this field is rendered
45 * as select tag, the value is not modified.
47 * @param mixed $choice An array if "multiple" is set to true, a scalar
50 * @return mixed An array
52 * @throws TransformationFailedException If the given value is not scalar or
53 * if the choices can not be retrieved.
55 public function transform($choice)
58 $values = $this->choiceList
->getValues();
59 } catch (\Exception
$e) {
60 throw new TransformationFailedException('Can not get the choice list', $e->getCode(), $e);
63 $index = current($this->choiceList
->getIndicesForChoices(array($choice)));
65 foreach ($values as $i => $value) {
66 $values[$i] = $i === $index;
69 if ($this->placeholderPresent
) {
70 $values['placeholder'] = false === $index;
77 * Transforms a checkbox/radio button array to a single choice.
79 * The input value is an array with the choices as keys and true/false as
80 * values, depending on whether a given choice is selected. The output
81 * is the selected choice.
83 * @param array $values An array of values
85 * @return mixed A scalar value
87 * @throws TransformationFailedException If the given value is not an array,
88 * if the recuperation of the choices
89 * fails or if some choice can't be
92 public function reverseTransform($values)
94 if (!is_array($values)) {
95 throw new TransformationFailedException('Expected an array.');
99 $choices = $this->choiceList
->getChoices();
100 } catch (\Exception
$e) {
101 throw new TransformationFailedException('Can not get the choice list', $e->getCode(), $e);
104 foreach ($values as $i => $selected) {
106 if (isset($choices[$i])) {
107 return $choices[$i] === '' ? null : $choices[$i];
108 } elseif ($this->placeholderPresent
&& 'placeholder' === $i) {
111 throw new TransformationFailedException(sprintf('The choice "%s" does not exist', $i));