我有 OutboundInvoice 实体的表单,在表单中我有 customer 选择字段,有 query_builder ,当选择客户时我需要在字段 invoicingType 中的单选按钮中更改选择数据 . 怎么办呢?
现在我使用symfony表单事件为字段 invoicing_address 'mapped' => false, 更改标签并且工作正常,单选按钮的相同决定不起作用
地址改了,单选按钮还没有,为什么?
class OutboundInvoiceForm extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('customer', 'entity', array(
'class' => Customer::class,
'property' => 'name',
'empty_value' => 'Choice Customer',
'query_builder' => function ($repository) {
/** @var CustomerRepository $repository */
return $repository->getAllQuery();
},
'required' => true
));
$formModifier = function (FormInterface $form, Customer $customer = null) {
if (null === $customer) {
$positions = '-';
$label = $positions;
$invoicingType = null;
} else {
$positions = $customer->getInvoicingAddress()
? $customer->getInvoicingAddress()->getFormattedAddress()
: '-';
$label = $positions;
$invoicingType = $customer->getInvoicingType()
? $customer->getInvoicingType()
: null;
}
$form
->add('invoicingType', 'entity', array(
'class' => InvoicingType::class,
'property' => 'name',
'data' => $invoicingType,
'query_builder' => function ($repository) {
/** @var InvoicingTypeRepository $repository */
return $repository->getAllQuery();
},
'required' => false,
'expanded' => true,
))
->add('invoicing_address', TextType::class, [
'mapped' => false,
'empty_data' => $positions,
'label' => $label
]);
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
$formModifier($event->getForm(), $data->getCustomer());
}
);
$builder->get('customer')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
$customer = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $customer);
}
);
$builder
->add('message')
->add('notes');
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => OutboundInvoice::class,
'csrf_protection' => false,
'edit' => false,
'terms_edit_data' => 0
));
}
/**
* @return string
*/
public function getName()
{
return 'economy_bundle_outbound_invoice';
}
模板和在js中替换的块
invoicing_address
{{ form_label(form.invoicing_address)}}
{{ form_widget(form.invoicing_address) }}
{{ form_label(form.invoicingType, 'invoicing_type*')}}
{{ form_widget(form.invoicingType) }}
这个我的js用元素替换了html
var $customer = $('#economy_bundle_outbound_invoice_customer');
$customer.change(function() {
var $form = $(this).closest('form');
var data = {};
data[$sport.attr('name')] = $sport.val();
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
$('#invoicing-address-container').replaceWith(
$(html).find('#invoicing-address-container')
);
}
});
});