我的构建形式女巫被动态修改。我已经按照文档(http://symfony.com/doc/current/form/dynamic_form_modification.html#form-events-submitted-data)进行了操作,并且我遇到了一个问题。
我的目标是制造"模型"当用户选择"品牌"字段。
以下是我的听众的样子:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('brand', EntityType::class, [
'class' => 'DEERCMS\BrandBundle\Entity\Brand',
'choice_label' => 'name',
'multiple' => false,
'expanded' => false,
]);
$formModifier = function (FormInterface $form, Brand $brand = null) {
$models = null === $brand ? array() : $brand->getModels();
$form->add('model', EntityType::class, array(
'class' => 'DEERCMS\ModelBundle\Entity\Model',
'choices' => $models,
'multiple' => false,
'expanded' => false,
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
// this would be your entity, i.e. SportMeetup
$data = $event->getData();
$formModifier($event->getForm(), $data->getBrand());
}
);
$builder->get('brand')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$brand = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $brand);
}
);
}
ajax调用正在发送,但它返回完全相同的html结构,我的目标是更新名为" model"的字段。这是模板:
{{ form_start(form, {'attr': {'id': 'form', 'class': 'form-horizontal', 'onChange': 'changed()' } }) }}
<div class="form-group">
<label class="col-md-3 control-label">Marka </label>
<div class="col-md-9">
{{form_row(form.brand, {'id': 'test', 'attr': { 'class': 'form-control'}}) }}
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Model </label>
<div class="col-md-9">
{{form_widget(form.model, {'id': 'test1', 'attr': { 'class': 'form-control'}}) }}
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-9">
<button type="submit" class="btn btn-success">{% if is_editing %}EDYTUJ {% else %}DODAJ{% endif %}</button>
</div>
</div>
{{form_end(form)}}
以及这里的AJAX电话
<script>
function changed() {
var brand = $('#test');
// ... retrieve the corresponding form.
var $form = $('#form');
console.log($form);
// Simulate form data, but only include the selected sport value.
var data = {};
data[brand.attr('name')] = brand.val();
// Submit data via AJAX to the form's action path.
jQuery.ajax({
url : $form.attr('action'),
type: "POST",
data: data,
success: function (html) {
console.log(html)
$("#test1").replaceWith(
// ... with the returned one from the AJAX response.
$(html).find("#test1")
);
// Position field now displays the appropriate positions.
}
});
}
</script>
当我执行console.log(html)时,它显示完全相同的html结构,因此它不包含&#34; model&#34;数据,应该从监听器中检索。
我已经检查了所有关系并且工作正常
答案 0 :(得分:0)
自己解决了!
它之所以不起作用的原因是我在form_start中有onChange()属性,它应该在form_row(form.brand)中