我正在尝试通过Symfony2和Ajax创建实体。当我尝试输入现有名称时,我希望在'名称'文本框。输入另一个正确的名称后,我想要成功删除和提交错误消息。我的代码没有提交正确的数据,但不断添加更多错误消息。
控制器
public function createSubmitAction(Request $request){
$collection = new Collection();
$user = $this->getUser();
$form = $this->createForm(
new CollectionType(),
$collection
);
$form->handleRequest($request);
$colname = $form["name"]->getData();
$existing = $this->getDoctrine()->getRepository('CollectionBundle:Collection')->findBy(['name' => $colname, 'user' => $user]);
if ($existing != NULL) {
return new JsonResponse(['error' => 'already exists']);
}
if ($form->isValid() && $form->isSubmitted()) {
$em = $this->getDoctrine()->getManager();
$collection->setUser($user);
$em->persist($collection);
$em->flush();
return new JsonResponse([
'id' => $collection->getId(),
'name' => $collection->getName()
]);
}
}
的Javascript
function createInObjectCollection(){
var $form = $('#create-in-object-form');
$($form).submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize()
}).done(function( data ) {
if (data.error){
$('<label class="form-error">Collection with such name already exists</label>').insertAfter('#mymini_collectionbundle_collection_name');
$('#mymini_collectionbundle_collection_name').addClass('error');
}
else{
$("#collection_bundle_add_to_collection option:first-child").after('<option value='+ data.id + '>' + data.name + '</option>');
$('#createCollectionModal').foundation('reveal', 'close');
}
});
});
}
答案 0 :(得分:2)
我有类似的情况。我使用EventListener:
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
\\...
}
);
您可以使用“SUBMIT”和“PRE_SUBMIT”之类的活动。