我正在尝试使用数组填充我的ChoiceType,但看起来它已经填充了ID而不是值。表单已正确显示,但选项为“0”,“1”...而不是数组中的名称。
这是我的控制者:
$categories = $this->getDoctrine()->getRepository('myBundle:Category')->findAll();
$techChoices = array();
$i = 0;
foreach($categories as $t) {
$techChoices[$i] = $t->getName();
$i = $i + 1;
}
$formOptions = array('categories' => $techChoices);
$document = new Document($categories);
$form = $this->createForm(DocumentType::class, $document, $formOptions);
这是我的buildForm:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', FileType::class)
->add('file_name', TextType::class)
->add('file_description', TextType::class)
->add('file_group', ChoiceType::class, array(
'choices' => $options['categories'],
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'categories' => array(),
));
}
答案 0 :(得分:1)
答案 1 :(得分:1)
在您的情况下显示类别的正确方法是使用EntityType,这将释放您的代码混乱。你不必再获得/传递类别了。
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('file', FileType::class)
->add('file_name', TextType::class)
->add('file_description', TextType::class)
->add('file_group', \Symfony\Bridge\Doctrine\Form\Type\EntityType::class, array(
// query choices from this entity
'class' => 'AppBundle:Category',
'choice_label' => 'name',
))
;
}
答案 2 :(得分:0)
你可以直接这样做:
$builder
->add('file', FileType::class)
->add('file_name', TextType::class)
->add('file_description', TextType::class)
->add('file_group', ChoiceType::class, array(
'choices' => 'here you pass your categories entities directly',
'choice_label' => 'name',
));
像那样,它将单独进行映射
答案 3 :(得分:0)
如果要直接在表单选择类型中使用数组,请参阅https://symfony.com/doc/current/reference/forms/types/choice.html#example-usage,或者如果要使用表(实体)中的数据,请参阅https://symfony.com/doc/current/reference/forms/types/entity.html#basic-usage
回答你的问题是数组格式应该是
[' data_to_be_seen1' => value1(id),' data_to_be_seen2' => value2(id),...]
(见第一个链接),
一切顺利