在提交下面的表单时,作为文本区域的字段“Body”在被调用时不会映射到 $message 对象 $form->getData();
。
我可以在 $request.parameters 中看到有两个值:
-form,这是一个包含表单值的数组,但缺少 textarea 值。
-Body,它是一个包含文本区域值的字符串。
为什么 Body 不是表单对象的一部分?
控制器动作:
class ContactController extends Controller { public function indexAction(Request $request) { $message = new Message(); $form = $this->createFormBuilder($message) ->add('Name', 'text', array('required' => true)) ->add('Email', 'email') ->add('Subject', 'text') ->add('Body', 'textarea') ->getForm(); $form->handleRequest($request); if ($form->isValid()) { // data is an array with "name", "email", and "message" keys $data = $form->getData(); } return $this->render('PhotographPhotoBundle:Contact:index.html.twig', array('form' => $form->createView())); } }
留言类:
class Message { protected $name; protected $subject; protected $body; protected $email; + setters and getters here }
表单模板
{# src/Photograph/PhotoBundle/Resources/views/Form/fields.html.twig #} {% block field_row %} {% spaceless %} {{ form_errors(form) }} {{ form_widget(form) }} {% endspaceless %} {% endblock field_row %} {% block email_widget %} <input type="email" {{ block('widget_attributes') }} value="{{ value }}" class="field-email form_field"> {% endblock %} {% block text_widget %} <input type="text" {{ block('widget_attributes') }} value="{{ value }}" class="field-name form_field"> {% endblock %} {% block textarea_widget %} <textarea name="field-message" {{ block('widget_attributes') }} cols="45" rows="5" class="field-message form_field">{{ value }}</textarea> {% endblock %}
表单视图
<form action="{{ path('PhotographPhotoBundle_contact') }}" method="post" class="feedback_form" > {{ form_errors(form) }} {{ form_widget(form.Name) }} <div class="clear"></div> {{ form_widget(form.Email, { 'attr': {'placeholder': 'email' }}) }} <div class="clear"></div> {{ form_widget(form.Subject, { 'attr': {'placeholder': 'sujet' }}) }} <div class="clear"></div> {{ form_widget(form.Body, { 'attr': {'placeholder': 'message' }}) }} <div class="clear"></div> <input value="envoyer votre message" type="submit" class="feedback_go" /> <div class="ajaxanswer"></div> {{ form_end(form) }}