我有一個字段類型實體呈現爲複選框,我想爲每個複選框添加一個textarea類型的字段,我該怎麼做?Symfony:如何將字段表單添加到孩子?
代碼:
// OfferType.php
$builder
->add('payment_method', new OfferPaymentType(), [
'required' => false,
'mapped' => false,
'expanded' => true,
'multiple' => true,
])
;
// OfferPaymentType.php
class OfferPaymentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('payment', null, [
'multiple' => true,
'expanded' => true,
'compound' => true,
])
;
$factory = $builder->getFormFactory();
$formModifier = function (FormInterface $form, $payments = null) use ($factory) {
foreach ($form as $child) {
//dump($child);die;
$child->add(
$factory->createNamed('metadata', 'textarea', null, [
'auto_initialize' => false,
'compound' => true,
]),
null,
['compound' => true]
);
}
};
$builder->get('payment')->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
$formModifier($event->getForm(), $data);
}
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'multiple' => true,
'expanded' => true,
'class' => 'AppBundle:OfferPayment',
'data_class' => 'AppBundle\Entity\OfferPayment',
'translation_domain' => 'app',
'compound' => true,
));
}
public function getName()
{
return 'offer_payment';
}
}
我認爲你可以通過以下步驟解決: 1-創建一個帶有兩個字段的新類型表單s - 複選框和文本區 2-使用創建的新類型的集合創建新表單。 但這取決於你需要做什麼。無論如何,你可以看看文檔:[如何嵌入表單集合](http://symfony.com/doc/current/cookbook/form/form_collections.html) – rck6982
這種方法的實體類型字段將是選擇框不復選框 –