As a website operator who is well-versed in the operation of AnQiCMS, I fully understand the importance of providing user interaction channels on the website.The user message form is a key tool for collecting feedback, answering questions, and establishing user relationships.In AnQiCMS, embedding and displaying a comment form through its flexible template engine is a direct and highly customizable process.This article will elaborate on how to implement this feature in AnQiCMS templates.
Understanding the core mechanism of the message form
AnQiCMS has built-in website message management functionality and provides special template tagsguestbookHelp us build the front-end message form. This tag is used to dynamically retrieve the comment fields configured on the back-end, allowing us to render user-friendly forms flexibly in the template.
While usingguestbookWhen labeling, we usually wrap it in an HTML<form>element. The submission address of the form is fixed to/guestbook.html, and must usePOSTmethod. Some core fields are required in the form, such asuser_name(Name of the person leaving a message),contact(Contact information) andcontent(Message content). In addition to these default fields, AnQiCMS also supports custom message fields that can be defined in the background, and these custom fields will also be passed throughguestbookTags dynamically provide us.
Embed the message form into the template.
To embed the comment form into the website template, we first need to create a template file for displaying comments. According to the AnQiCMS template conventions, the comment form page is usually stored in the template directory.guestbook/index.htmlIn the file. If your theme template adopts a flattened mode, it can beguestbook.html.
We will use in the template file,guestbookThe tag traverses all the message fields configured in the background and dynamically generates the corresponding HTML form elements. The following is a complete code segment demonstrating how to build a dynamic message form that adapts to the background configuration:
<form method="post" action="/guestbook.html">
<input type="hidden" name="return" value="html"> {# 可选:指定后台返回HTML格式,也可设置为json #}
{% guestbook fields %}
{% for item in fields %}
<div class="form-group">
<label for="{{ item.FieldName }}">{{ item.Name }}:</label>
<div>
{% if item.Type == "text" or item.Type == "number" %}
<input type="{{ item.Type }}" name="{{ item.FieldName }}" id="{{ item.FieldName }}"
{% if item.Required %}required{% endif %}
placeholder="{{ item.Content }}" autocomplete="off" class="form-control">
{% elif item.Type == "textarea" %}
<textarea name="{{ item.FieldName }}" id="{{ item.FieldName }}"
{% if item.Required %}required{% endif %}
placeholder="{{ item.Content }}" rows="5" class="form-control"></textarea>
{% elif item.Type == "radio" %}
{% for val in item.Items %}
<label class="radio-inline">
<input type="radio" name="{{ item.FieldName }}" value="{{ val }}"
{% if loop.first and item.Required %}checked{% endif %}> {{ val }}
</label>
{% endfor %}
{% elif item.Type == "checkbox" %}
{% for val in item.Items %}
<label class="checkbox-inline">
<input type="checkbox" name="{{ item.FieldName }}[]" value="{{ val }}"> {{ val }}
</label>
{% endfor %}
{% elif item.Type == "select" %}
<select name="{{ item.FieldName }}" id="{{ item.FieldName }}" class="form-control">
{% for val in item.Items %}
<option value="{{ val }}">{{ val }}</option>
{% endfor %}
</select>
{% endif %}
</div>
</div>
{% endfor %}
{% endguestbook %}
{# 验证码区域,如果后台开启了验证码,这里是必须的 #}
<div class="form-group captcha-area">
<label for="captcha">验证码:</label>
<div class="input-group">
<input type="hidden" name="captcha_id" id="captcha_id">
<input type="text" name="captcha" id="captcha" required placeholder="请输入验证码" class="form-control">
<span class="input-group-btn">
<img src="" id="get-captcha" alt="验证码" class="captcha-img" style="cursor: pointer;">
</span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">提交留言</button>
<button type="reset" class="btn btn-default">重置</button>
</div>
</form>
{# 验证码刷新JS #}
<script>
document.addEventListener('DOMContentLoaded', function() {
const getCaptchaBtn = document.getElementById('get-captcha');
const captchaIdField = document.getElementById('captcha_id');
function fetchCaptcha() {
fetch('/api/captcha')
.then(response => response.json())
.then(res => {
if (res.code === 0 && res.data) {
captchaIdField.value = res.data.captcha_id;
getCaptchaBtn.src = res.data.captcha;
} else {
console.error('获取验证码失败:', res.msg);
}
})
.catch(err => console.error('获取验证码请求失败:', err));
}
if (getCaptchaBtn) {
getCaptchaBtn.addEventListener('click', fetchCaptcha);
fetchCaptcha(); // 页面加载时自动获取一次验证码
}
});
</script>
In the code above,guestbook fieldsThe label will loop through each comment field configured on the backend. For eachitem(field), we can access itsName(display name of the field),FieldName(field name when the form is submitted),Type(Field type),Required(Is required) andContent(Default value or placeholder). Based onTypeThe different, we have generated different HTML input elements, such as text boxes, number input boxes, multi-line text areas, radio buttons, checkboxes, and drop-down selection boxes.item.ItemsThe attribute is used for single selection, multiple selection, and dropdown types, it includes all options.
It is worth noting that,RequiredThe attribute is converted to HTML.requiredThe attribute, to ensure that the user has filled in the required information before submitting.returnHidden field is used to inform the server of the expected response format, the default ishtmlcan also be set tojsonfor convenient asynchronous processing on the front end.
Integrated message captcha (optional)
To prevent spam and robot submissions, AnQiCMS provides a message captcha function.If you enable this feature in the background, it becomes crucial to embed the captcha in the front-end template.
First, make sure you have enabled the captcha in the AnQiCMS background message settings.
Secondly, you need to add the HTML structure and JavaScript code related to the captcha in the comment form. As shown in the above code example, specifically:
A hiddeninputField used to store the ID of the captcha (captcha_id)
A textinputField used for user input of the captcha (captcha)
AimgLabel used to display the captcha image, itssrcThe property will be loaded dynamically through JavaScript.
The accompanying JavaScript code will automatically request and display the captcha when the page is loaded, and refresh the captcha when the user clicks on the captcha image. The captcha image passes.fetch('/api/captcha')The interface is obtained, this interface will returncaptcha_idandcaptchaImage URL.
Form submission and user experience
After the user fills in and submits the form, the data will be sent to/guestbook.html.The AnQiCMS backend will receive and process this data, including executing captcha verification, saving comments to the database, and possibly triggering email notifications (if the backend is configured to send reminders).
If successful after submission,returnfield tohtmlThe server may redirect back to the message page and display a success message; if set tojsonFront-end can handle the returned JSON data through JavaScript, such as popping up a prompt box or clearing the form.When designing the front-end user experience, it is very important to consider the feedback after form submission, which allows users to clearly know whether their operation was successful.
By following these steps and code examples, you should be able to successfully embed and display a fully functional user message form in the AnQiCMS template, providing a solid foundation for website user interaction.
Frequently Asked Questions (FAQ)
How to customize the style and layout of the comment form fields?You can customize the style and layout of the comment form in two main ways:
- CSS style customizationIn the above code example, form elements used basic HTML structure. You can customize it according to your website theme and design requirements, for
div.form-group/label/input/textareaAdd custom CSS classes to elements such as buttons (for exampleform-control/btn), then define the styles for these classes in your theme CSS file. - HTML structure adjustment:
guestbookTags are mainly used to dynamically generate the input field itself. You can{% for item in fields %}loop internally, based onitem.FieldNameoritem.TypePerform more detailed conditional judgments to apply different HTML wrapping structures to specific fields, such as placing them in differentdivTo achieve multi-column layout, or add additional description text for specific fields.
2. Can I add additional fields not configured in the AnQiCMS backend to the comment form?It is not recommended to add extra fields not configured in the AnQiCMS backend directly in the front-end template. AnQiCMS'sguestbookThe label is intended to work with the background message field management feature to ensure that the submitted data can be correctly identified and stored by the system.If you add fields that are not configured in the background, the data of these fields is usually not saved by AnQiCMS.If you need to add a field, the most recommended method is to go to the "Function Management" -> "Website Message Management" in the AnQiCMS background, and configure it through the "Custom Message Field" function.guestbookLabel recognition and automatic rendering, and the data can also be correctly processed and stored by the background.
3. After the user submits a message, how does the website send me a notification?AnQiCMS supports configuring the留言email reminder function.You can find the "Email Reminder Management" in the "Function Management" on the backend, where you can configure SMTP server information and the email address for receiving message notifications.Once configured, when a user submits a new message through the website's contact form, the system will automatically send an email notification to the email address you specify, making it convenient for you to handle user feedback in a timely manner.