【发布时间】:2015-11-13 10:11:34
【问题描述】:
我正在尝试通过 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');
}
});
});
}
【问题讨论】:
标签: javascript php jquery ajax symfony