我已经在Silverstripe中创建了一个前端表单。它的工作原理是记录数据,如果有任何错误,它会重定向回来,而不保存数据。然而,我面临的问题是验证消息没有正确显示。当我使用$Form
变量在前端显示表单时,验证和一切都工作正常。我想做的是用<% control Form %>
控制表单的布局。这是因为表单的设计方式。
<% control Form %>
<form class="wrap" $FormAttributes>
<% if $Message %>
<p id="{$FormName}_error" class="message $MessageType">$Message</p>
<% else %>
<p id="{$FormName}_error" class="message $MessageType" style="display: none"></p>
<% end_if %>
<fieldset>
<div class="member-details col lg-mobile-12 tablet-6 sm-desktop-6 md-desktop-6">
<% if ModTest == 'false' %>
<div class="field wrap">
<% control $Fields.dataFieldByName(ClientName) %>
<label class="title">$Title</label>$Field
<% end_control %>
</div>
<% end_if %>
<div class="field wrap">
<% control $Fields.dataFieldByName(FirstName) %>
<label class="title">$Title</label>$Field
<% end_control %>
</div>
<div class="field wrap">
<% control $Fields.dataFieldByName(Surname) %>
<label class="title">$Title</label>$Field
<% end_control %>
</div>
<% if $Fields.dataFieldByName(Address) %>
<div class="field address wrap">
<% control $Fields.dataFieldByName(Address) %>
<label class="title">$Title</label>
<% end_control %>
<div class="address-fields wrap">
$Fields.dataFieldByName(Address)
$Fields.dataFieldByName(Suburb)
$Fields.dataFieldByName(State)
$Fields.dataFieldByName(PostCode)
</div>
</div>
<% end_if %>
<% control $Fields.dataFieldByName(Phone) %>
<div class="field wrap">
<label class="title">$Title</label>$Field
</div>
<% end_control %>
<% control $Fields.dataFieldByName(Email) %>
<div id="$HolderID" class="field wrap <% if $extraClass %> $extraClass<% end_if %>">
<label class="title" for="$ID">$Title</label>
$Field
<% if $Message %><span class="message $MessageType">$Message</span><% end_if %>
</div>
<% end_control %>
</div>
<div class="password col lg-mobile-12 tablet-6 sm-desktop-6 md-desktop-6">
<div class="field confirmedpassword">
$Fields.dataFieldByName(Password)
</div>
</div>
$Fields.dataFieldByName(SecurityID)
</fieldset>
<div class="col lg-mobile-12 tablet-12 sm-desktop-12 md-desktop-12">
<% if $Actions %>
<div class="Actions">
<% loop $Actions %>
$Field
<% end_loop %>
</div>
<% end_if %>
</div>
</form>
<% end_control %>
在模板中编写所有表单标记-就像您所做的那样-几乎违背了表单呈现和模板的目的。它也非常不灵活,因为你必须在模板中添加新添加的字段,而不是直接将它们添加到表单中。
就我个人而言,我会使用CompositeField
来分组您的字段(例如。包装多个字段的字段),并在需要自定义模板的字段上使用setTemplate
。
我认为您应该能够实现与自定义模板和复合字段的模板非常相似的输出。这样你就可以把$Form
放到你的模板中了。
要获取每个字段级别的消息,您需要处理每个字段对象。
<% with $Fields.dataFieldByName(Name) %>
<div>
<label>Name</label>
<input name="Name" type="text" id="name" placeholder="Name" required>
<% if $Message %><span>$Message</span><% end_if %>
</div>
<% end_with %>
在with中添加$Debug
将列出该字段中可用的内容,这对于添加css id和其他CMS控制文本非常有用。