It seems to be using the defacto choicetype docs rather than detailing how to select certain entities for the preferred choices.
https://symfony.com/doc/current/reference/forms/types/entity.html
Furthermore it seems that preferred_choice does not work the way it is documented. I need it and i do not find the trick to make it work.
@jamm-kevin Unfortunately you can't pass in id's of the entities that you want (you could with symfony 3 I believe). Instead you have to pass in the actual entity, e.g. (untested) 'preferred_choices' => [$repo->find(1), $repo->find(2)]
Are we sure the docs are wrong? It first show a simple array example ... but then it shows you an example based on a callback function. That's what you should use to do return in_array($value->someGetter(), ['preferred_choice_1', '...']); There's a final example that mentions that you can also use a property path on an object to also return true/false.
I'd say it's OK like it is ... but we could expand the code of the second example to show something similar to what you'll use in an EntityType example.
I agree that this example doesn't fit to this form type:
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...
$builder->add('language', ChoiceType::class, array(
'choices' => array(
'English' => 'en',
'Spanish' => 'es',
'Bork' => 'muppets',
'Pirate' => 'arr',
),
'preferred_choices' => array('muppets', 'arr'),
));
Instead, it should be something like this:
use App\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...
$builder->add('users', EntityType::class, array(
'class' => User::class,
'preferred_choices' => $group->getPreferredUsers(),
));
and perhaps explain in this case that it must pass the instances of the User::class.
@ChangePlaces Thanks a lot ; passing entire instances of my entities does the trick.
Definitely a documentation issue for me. I would never EVER had the idea to pass entire entities since the doc pass ids or string values.
@javiereguiluz I think the above can be put in the documentation with a brief mention. Maybe there are other ways of showing the preferred choices that I'm not aware of.
Fixed by #10072.
Most helpful comment
@jamm-kevin Unfortunately you can't pass in id's of the entities that you want (you could with symfony 3 I believe). Instead you have to pass in the actual entity, e.g. (untested)
'preferred_choices' => [$repo->find(1), $repo->find(2)]