AnQi CMS provides a flexible mechanism to handle the interactive content of the website, among which the message form is an important bridge for communication with users.When we need to collect diversified information from users, we often create custom comment fields.How to accurately call and display these custom message form fields configured in the backend template on the website front-end, which is the key to achieving personalized user experience.
In AnQiCMS, the display of message form fields mainly depends on the use of template tags. The system is built with a dedicated module for handling message forms.guestbookThe label, which can extract all the field information of the comments configured in the background, for the use of the front-end template.
Understand the structure of the comment form fields
Firstly, we need to introduce the template.guestbookA tag to get all the field data of the comment form. This tag is often used with a variable name, for example{% guestbook fields %}. Here,fieldsis an array object containing all the field information of the comment form.
Forfieldsarrayitem(i.e. each comment field), we can access the following key properties to build the form:
Name: the display name of the field, for example 'Your Name', 'Phone Number'.FieldNameThe unique identifier of the field, used for HTML form elementsnameThe attribute, the backend receives data through this name.TypeThe type of the field determines which HTML input element is rendered, such astext(Single-line text),number(Number),textarea(Multi-line text),radio(Single selection),checkbox(Select multiple) orselect(Dropdown select).Required: A boolean value indicating whether the field is required or not.Content: The default value or placeholder text for the field.Items: Forradio/checkboxorselectType field,Itemsis an array containing all optional values.
By traversing thisfieldsarray, we can determine eachitemofTypeThe property dynamically generates the corresponding HTML form elements to ensure that the front-end form is consistent with the fields configured in the background.
Build a comment form in the template.
We need to use an HTML to display these fields on the web<form>the tag and use it.actionproperty points to/guestbook.htmlThis is the standard interface for receiving message data in AnQiCMS backend. Within the form, we can pass an array and generate corresponding input elements for each field.forto loop throughguestbookthe tags returned byfieldsAn array can be passed and corresponding input elements for each field can be generated.
The following is a general template code example that demonstrates how to render different forms of form elements based on field type:
<form method="post" action="/guestbook.html">
<input type="hidden" name="return" value="html"> {# 告诉后端以HTML形式返回结果 #}
{% guestbook fields %}
{% for item in fields %}
<div>
<label for="{{ item.FieldName }}">{{ item.Name }}{% if item.Required %}<span style="color: red;">*</span>{% endif %}</label>
<div>
{% if item.Type == "text" or item.Type == "number" %}
<input type="{{ item.Type }}" id="{{ item.FieldName }}" name="{{ item.FieldName }}" {% if item.Required %}required{% endif %} placeholder="{{ item.Content }}" autocomplete="off">
{% elif item.Type == "textarea" %}
<textarea id="{{ item.FieldName }}" name="{{ item.FieldName }}" {% if item.Required %}required{% endif %} placeholder="{{ item.Content }}" rows="5"></textarea>
{% elif item.Type == "radio" %}
{% for val in item.Items %}
<input type="{{ item.Type }}" id="{{ item.FieldName }}_{{ loop.index }}" name="{{ item.FieldName }}" value="{{ val }}" {% if item.Required %}required{% endif %}>
<label for="{{ item.FieldName }}_{{ loop.index }}">{{ val }}</label>
{% endfor %}
{% elif item.Type == "checkbox" %}
{% for val in item.Items %}
<input type="{{ item.Type }}" id="{{ item.FieldName }}_{{ loop.index }}" name="{{ item.FieldName }}[]" value="{{ val }}">
<label for="{{ item.FieldName }}_{{ loop.index }}">{{ val }}</label>
{% endfor %}
{% elif item.Type == "select" %}
<select id="{{ item.FieldName }}" name="{{ item.FieldName }}" {% if item.Required %}required{% endif %}>
{% for val in item.Items %}
<option value="{{ val }}">{{ val }}</option>
{% endfor %}
</select>
{% endif %}
</div>
</div>
{% endfor %}
<div>
{# 如果后台开启了留言验证码功能,此处将显示验证码输入框及刷新按钮 #}
{# 详细集成方法请参考AnQiCMS文档中关于“留言验证码使用标签”的部分 #}
{# 示例如下,通常需要JavaScript来动态加载和刷新验证码图片 #}
{#
<div style="display: flex; clear: both">
<input type="hidden" name="captcha_id" id="captcha_id">
<input type="text" name="captcha" required placeholder="请填写验证码" class="layui-input" style="flex: 1">
<img src="" id="get-captcha" style="width: 150px;height: 56px;cursor: pointer;" alt="验证码" />
<script>
document.getElementById('get-captcha').addEventListener("click", function (e) {
fetch('/api/captcha')
.then(response => response.json())
.then(res => {
document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id);
document.getElementById('get-captcha').setAttribute("src", res.data.captcha);
}).catch(err => console.error('Failed to load captcha:', err));
});
document.getElementById('get-captcha').click();
</script>
</div>
#}
<button type="submit">提交留言</button>
<button type="reset">重置</button>
</div>
{% endguestbook %}
</form>
The code first introduces a field namedreturnwhich has a hidden field value ofhtmlThis indicates that after the backend has processed the comments, it will return an HTML response instead of JSON or other formats. Next, through{% guestbook fields %}tag to get all the comment fields and useforLoop through. Inside the loop, according toitem.Typethe value, useif-elifstructure to generate the corresponding<input>/<textarea>or<select>elements. Forradioandcheckboxas well asselecttype, further iteration will be performeditem.ItemsAn array is used to generate each option. Finally, the form contains submit and reset buttons.
It is noteworthy that the template system of AnQiCMS is very flexible, you can freely adjust the HTML structure and CSS style according to your design needs, without being constrained by the simpledivandlabelCan create a user interface that meets the aesthetic standards of your website.
Client-side validation and security considerations
In the above code example, we used HTML5'srequiredThe property to implement basic client-side required validation. Whenitem.RequiredWithtruethe attribute is added to the corresponding form element. This provides basic feedback before the user submits.
In addition, to prevent spam submissions, AnQiCMS supports integrated captcha functionality.If you have enabled comment captcha in the background, you need to add an input box and a refresh button to the comment form, and work with front-end JavaScript code to dynamically load and refresh the captcha image./api/captchaThe interface is used to obtain the verification code ID and image URL, and it needs to be submitted in the formcaptcha_idandcaptchaThese fields. This enhances the security of the form
By following these steps, you can flexibly and efficiently call and display the user submitted comment form fields in the AnQiCMS template, providing a high-quality interactive experience for your website visitors.
Frequently Asked Questions (FAQ)
How to add custom fields to the留言表单in AnQiCMS backend? Usually, AnQiCMS provides an entry for custom message field configuration under the "Function Management" module, "Website Message Management" module. You can add new fields according to business requirements, such as "occupation", "company name", etc., and set their types (single line text, multiple choice, etc.), whether required, and default values.
guestbookTags are available in the front-end template.How can I only display some fields in the留言表单?In the template,
guestbookthe tag will return all configured comment fields. If you only want to display a part of them, you can usefieldsconditions to filter whileifiterating through the array. For example, to display onlyFieldNameYou can write for the 'user_name' and 'content' fields like this:{% for item in fields %}{% if item.FieldName == "user_name" or item.FieldName == "content" %}{# 渲染这些特定字段的HTML #}{% endif %}{% endfor %}Or, if you know the name of the field to display, you can also directly encode the HTML structure of these fields without usingforto generate dynamically.except for HTML5's
requiredCan the attribute add more complex client-side validation to the comment form field?HTML5'srequiredThe attribute provides basic required item validation.For more complex validation logic, such as phone number format, email format, word limits, etc., you need to use JavaScript to implement client-side validation.This usually involves intercepting the form submission event before the form is submitted, then using JavaScript to check if each field's value meets the predefined rules.Many frontend frameworks or libraries (such as jQuery Validation, VeeValidate, etc.) can help you easily implement these complex client-side validations.