繁体   English   中英

Symfony2:生成表单的HTML5属性

[英]Symfony2: HTML5 attributes for generated form

我是Symfony2的新手,现在正在尝试构建表单。 我有一个Message类,并且表单中的数据应创建一个Message对象。

我的问题是字段不是必需的,尽管在调用createFormBuilder时已在控制器中明确指定了它。

但是会触发电子邮件的HTML5验证程序。

第二个问题是占位符属性不起作用。 尽管我已在视图中进行了设置,但它并未添加到字段中。

  1. 控制器动作:

     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())); } } 
  2. 讯息类别:

     class Message { protected $name; protected $subject; protected $body; protected $email; + setters and getters here } 
  3. 表格模板

      {# 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('attributes') }} value="{{ value }}" class="field-email form_field"> {% endblock %} {% block text_widget %} <input type="text" {{ block('attributes') }} value="{{ value }}" class="field-name form_field"> {% endblock %} {% block textarea_widget %} <textarea name="field-message" {{ block('attributes') }} cols="45" rows="5" class="field-message form_field">{{ value }}</textarea> {% endblock %} 
  4. 表单视图

      <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) }} 

将所有非必需列的required属性设置为false,并添加attr属性以添加占位符

$form = $this->createFormBuilder($message)
    ->add('Name', 'text', array('required' => false))
    ->add('Email', 'email', array('required' => false, 'attr' => array('placeholder' => 'some text here')))
    ->add('Subject', 'text')
    ->add('Body', 'textarea')
    ->getForm();

您的表单主题模板中有一个错误。 该块称为widget_attributes

{% block text_widget %}
    <input type="text" {{ block('widget_attributes') }} value="{{ value }}" class="field-name form_field">
{% endblock %}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM