我有以下用例:
用户可以选择从下拉选项,但如果他们想选择别的东西,他们可以选择“其他”,这带来了一个JavaScript prompt()
,然后将其添加为option
到select
和选择。
我的问题是关于如何在加载页面时将此值加载到select中。我可以看到我可以使用
$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));
}
});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句