修改 Symfony 2 表单行为
我正在使用 Symfony 2。
我的表单工作方式如下:
表单以 Ajax (JQuery) 提交
如果我的表单中有错误,我收到包含所有错误消息的 XML 响应
<errors> <error id="name">This field cannot be blank</error> <error id="email">This email address is not valid</error> <error id="birthday">Birthday cannot be in the future</error> </errors>
- 如果我的表单中没有错误,我会收到带有重定向 URL 的 XML 响应
<redirect url="/confirm"></redirect>
- 我的问题是:我怎样才能“永远”改变Symfony 2中表单的行为,以便我可以使用如下所示的控制器:
public function registerAction(Request $request) { $member = new Member(); $form = $this->createFormBuilder($member) ->add('name', 'text') ->add('email', 'email') ->add('birthday', 'date') ->getForm(); if($request->getMethod() == 'POST') { $form->bindRequest($request); if($form->isValid()) { // returns XML response with redirect URL } else { // returns XML response with error messages } } // returns HTML form }
感谢您的帮助,
问候,
I am using Symfony 2.
The way my forms are working is like the following :
Forms are submitted in Ajax (JQuery)
If there are errors in my form, I receive an XML response with all error messages
<errors> <error id="name">This field cannot be blank</error> <error id="email">This email address is not valid</error> <error id="birthday">Birthday cannot be in the future</error> </errors>
- If there is no error in my form, I receive an XML response with redirect URL
<redirect url="/confirm"></redirect>
- My question is : how can I change "forever" the behavior of forms in Symfony 2 so that I could use a controller like the following :
public function registerAction(Request $request) { $member = new Member(); $form = $this->createFormBuilder($member) ->add('name', 'text') ->add('email', 'email') ->add('birthday', 'date') ->getForm(); if($request->getMethod() == 'POST') { $form->bindRequest($request); if($form->isValid()) { // returns XML response with redirect URL } else { // returns XML response with error messages } } // returns HTML form }
Thanks for your help,
Regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
表单处理程序也是我的做法。验证 formHandler 中的表单,并根据 formHandler 的响应在控制器中创建 json 或 xml 响应。
每个字段只返回 1 条错误消息,但它对我有用。
A form handler is how I do it as well. Validate the form in the formHandler and create your json or xml response in the controller depending on the response from the formHandler.
This only returns 1 error message per field but it does the trick for me.
考虑将此逻辑封装在“表单处理程序”服务中,类似于 FOSUserBundle 中所做的操作:
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Form/Handler/RegistrationFormHandler.php
Consider encapsulating this logic in a "form handler" service, similar to what is done in FOSUserBundle:
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Form/Handler/RegistrationFormHandler.php