Answer the question
In order to leave comments, you need to log in
How to use choices in forms with ArrayCollection but not with Entity but with regular class?
Hello.
There is a collection of Skills objects (it contains both getters and setters), which are formed from a YML file.
There is my field type (SET) in the User entity:
/**
* @ORM\Column(type="skills", nullable=true)
* @var ArrayCollection
*/
private $skills;
//@UserType
->add('skills', 'collection', array(
'type' => 'choice',
'options' => array(
'choice_list' => new ObjectChoiceList(
$this->skillManager->getAllSkills()->toArray(),
'name',
array(),
null,
'alias'
),
'multiple' => true
)
));
//@UserType
->add('skills', 'choice', array(
'choice_list' => new ObjectChoiceList(
$this->skillManager->getAllSkills()->toArray(),
'name',
array(),
null,
'alias'
),
'multiple' => true
));
Answer the question
In order to leave comments, you need to log in
In short, I quickly made this miracle:
class ChoicesCollectionToArrayTransformer implements DataTransformerInterface
{
private $choiceList;
public function __construct(ChoiceListInterface $choiceList)
{
$this->choiceList = $choiceList;
}
public function transform($collection)
{
if (null === $collection) {
return array();
}
if (is_array($collection)) {
return $collection;
}
if (!$collection instanceof Collection) {
throw new TransformationFailedException('Expected a Doctrine\Common\Collections\Collection object.');
}
return $this->choiceList->getValuesForChoices($collection->toArray());
}
public function reverseTransform($array)
{
if ('' === $array || null === $array) {
$array = array();
} else {
$array = (array) $array;
}
$choices = $this->choiceList->getChoicesForValues($array);
if (count($choices) !== count($array)) {
throw new TransformationFailedException('Could not find all matching choices for the given values');
}
return new ArrayCollection($choices);
}
}
$skillsChoiceList = new ObjectChoiceList(
$this->skillManager->getAllSkills()->toArray(),
'name',
array(),
null,
'alias'
);
$builder ->add('skills', 'choice', array(
'choice_list' => $skillsChoiceList,
'multiple' => true
));
$builder->get('skills')->resetViewTransformers()->addViewTransformer(new ChoicesCollectionToArrayTransformer($skillsChoiceList));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question