编辑:我有一个表单模板,我将其包含在模式框中。单击按钮打开模态时,它可以正常工作。
<button href="{{ path('monteal_backend_company_add') }}" data-modal-id="add-company" class="primary add-company-launch">Add Company</button>
<div id="add-company" class="modal display-hidden">
<div class="content pad-10">
<a href="" class="modal-close float-right">
<i class="material-icons md-18">close</i>
</a>
<h3 class="font-bold pad-top-15">Add Company</h3>
<hr>
{{ render(controller('MontealBundle:Admin/Backend/Company:new')) }}
</div>
</div>
模板内部我有..
{% if not form.vars.valid %}
<p class="alert note-error">
There are errors in your form. Please check the fields marked in red.
</p>
{% endif %}
{{ form_errors(form) }}
<div class="sections pb30 pt10">
<fieldset class="col span6 alert {% if form_errors(form.name) is not empty %}error{% endif %}">
<label for="" class="input-required">
<strong>Name <span class="highlight-red">*</span></strong>
</label>
{{ form_widget(form.name) }}
{% if not form.name.vars.valid %}
<p class="mt10" style="color: #DC2B1B;">{{ form.name.vars.errors[0].message }}</p>
{% endif %}
</fieldset>
</div>
尽可能存在已与模板合并的验证脚本。
问题是当我提交表单时,验证消息没有显示在我的模态框中。
这是我的Ajax事件。
<script>
$(function () {
$('.withdropdown').dropdown();
$('.add-company-launch').modal();
$('#company-form').submit(function(e) {
var formUrl = "{{ path('monteal_backend_company_ajax') }}";
var formData = new FormData(this)
$.ajax({
url: formUrl,
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data, textStatus, jqXHR)
{
if(data['status'] === 'success'){
alert('success');
} else {
$('#add-company').html(data['html']);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault();
});
})
</script>
{% endblock %}
这是我的控制器。
public function newAction() {
$company = new Company();
$form = $this->createForm(CompanyForm::class, $company);
return $this->render('Admin/Backend/Company/new.html.twig', array(
'form'=>$form->createView()
));
}
public function ajaxAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}
$company = new Company();
$form = $this->createForm(CompanyForm::class, $company);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($company);
$em->flush();
return new JsonResponse(array(
'status' => 'success'), 200
);
}
$html = $this->renderView("Admin/Backend/Company/new.html.twig", array(
'form'=>$form->createView()
));
$data = array('status' => 'error', 'html' => $html);
return new JsonResponse($data, 400);
}
这是我的路线。
monteal_backend_company_add:
path: /admin/company/add
defaults: { _controller: MontealBundle:Admin/Backend/Company:new }
monteal_backend_company_ajax:
path: /admin/company/ajax
defaults: { _controller: MontealBundle:Admin/Backend/Company:ajax }
有人可以解释为什么验证消息没有以模态/形式显示。