如何从symfony select类型获取选项
我有以下用例: 用户可以从下拉列表中选择选项,但是如果他们想选择其他内容,可以选择“其他”,这会弹出一个Javascript提示,然后将其作为选项添加到“选择和选定”列表中 我的问题是如何在加载页面时将此值加载到select中。我知道我可以用如何从symfony select类型获取选项,symfony,Symfony,我有以下用例: 用户可以从下拉列表中选择选项,但是如果他们想选择其他内容,可以选择“其他”,这会弹出一个Javascript提示,然后将其作为选项添加到“选择和选定”列表中 我的问题是如何在加载页面时将此值加载到select中。我知道我可以用 $builder->addEventListener( FormEvents::PRE_SET_DATA, 向列表中添加额外的元素,但如何获取现有元素的列表?我肯定我不必再对它们进行编码,但我找不到获取选项列表的路径 以下是下拉列表的类别
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
向列表中添加额外的元素,但如何获取现有元素的列表?我肯定我不必再对它们进行编码,但我找不到获取选项列表的路径
以下是下拉列表的类别:
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class HeatGeneratedFormType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array('choices'=>
array(
null=> 'Select',
'Grasses / Straw' => 'Grasses / Straw',
'Wood Chip' => 'Wood Chip',
'Wood Logs' => 'Wood Logs',
'Wood Pellets' => 'Wood Pellets',
'Other' => 'Other'
)
)
);
}
public function getParent()
{
return 'choice';
}
public function getName()
{
return 'HeatGenerated';
}
}
因此,重新表述我的问题,对于这段代码:
if (!in_array($object->getHeatGenerated(), $form->get('heatGenerated')->getChoices()) {
$form->get('heatGenerated')->addChoice($object->getHeatGenerated());
}
->getChoices和->addChoice不是真正的方法,我用什么来获取和编辑选项列表 以下是我所做的:
class MyFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// other fields chopped
->add('myField', new CustomChoiceFormType()) // This type has the preset choices
;
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
$choices = $form->get('myField')->getConfig()->getOption('choices');
$choice = $data->getMyField();
if (!in_array($choice, $choices)) {
$newChoices = array_merge($choices, array($choice=>$choice)); // Need to add the key and the value, for me these are the same, but ofcourse they could be different
$form->remove('myField');
$form->add('myField', 'choice', array('choices'=>$newChoices));
}
});
}
}
尝试$form->getConfig->getOption'choices';谢谢@user2268997,太好了,有没有办法添加选项?我还没有找到。我要做的是用新的选项再次添加字段。