How to render and process the message form fields in AnQiCMS template?

Calendar 👁️ 65

As an experienced CMS website operation personnel of an enterprise, I am very clear about the importance of high-quality content and smooth user experience in attracting and retaining users.The comment form is an important bridge for website interaction with users, and its correct rendering and processing in the template is directly related to whether users can conveniently and quickly contact us.Below, I will elaborate on how to render and process the comment form fields in the AnQiCMS template.

The location of the comment form template file

In AnQiCMS, the comment form usually has a dedicated template file to carry its content. According to the basic conventions of the system template creation, the template file of the comment page is usually located in the template directory.guestbook/index.htmlOr in the flattened modeguestbook.htmlUnderstanding this position is the first step in customization and development

UseguestbookLabel to get form fields

AnQiCMS provides a namedguestbookThe template tag is specifically used to retrieve the background configuration of the message form field.This tag allows us to dynamically render the corresponding form elements on the front end based on the flexible configuration of the backend.

The basic usage of tags is:{% guestbook fields %}...{% endguestbook %}. Here,fieldsThis is the variable name defined for the array of form fields. This tag can accept an optional parametersiteIdUsed to call the specified site's comment form data in a multi-site environment, but usually not necessary for a single site.

fieldsA variable is an array object, which means we need to go throughforLoop through it to render each form field one by one.

Understand the structure of form fields deeply.

Inforthe loop,fieldseach element of the arrayitemIt represents a comment form field, it contains the following key properties, which guide us on how to correctly render the form:

  • Name: The display name of the form field, for example, "Your name", "Contact information", etc., which is the label text that users see on the page.
  • FieldName: Form field variable name, which will be used as HTMLinput/textareaorselectelementnameAttribute value, used to submit data to the backend.
  • Type: The type of form field, which determines which HTML form element we should render. AnQiCMS supports six types:
    • text(Text type)
    • number(Numeric type)
    • textarea(Multiline text type)
    • radio(Single selection type)
    • checkbox(Multiple selection type)
    • select(Dropdown selection type)
  • Required: A boolean value indicating whether this field is required. When its value istrueWhen, we should add to the HTML elementrequiredProperty.
  • Content: The default value or placeholder text for form fields, for text input boxes or multi-line text boxes, this is usually asplaceholderthe value of the attribute.
  • Items: Only when the form type isradio/checkboxorselectdoes this array exist. It contains all the available option values, and we need to traverse this array again to render these options.

Render the comment form dynamically

Combining the structure of the above fields, we can write general code in the template to dynamically generate forms. The core idea is to useforLoop throughfieldsThen, based onitem.TypeThe value is used to make conditional judgments, rendering different HTML form elements.

The following is a detailed code snippet that shows how to dynamically render forms based on field types.

<form method="post" action="/guestbook.html">
    {% guestbook fields %}
        {% for item in fields %}
        <div class="form-group">
            <label for="{{ item.FieldName }}">{{ item.Name }}{% if item.Required %}<span class="text-danger">*</span>{% endif %}</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 item.Required and loop.first %}required{% 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 }}" {% if item.Required and loop.first %}required{% endif %}> {{ val }}
                    </label>
                    {% endfor %}
                {% elif item.Type == "select" %}
                <select name="{{ item.FieldName }}" id="{{ item.FieldName }}" class="form-control" {% if item.Required %}required{% endif %}>
                    {% for val in item.Items %}
                    <option value="{{ val }}">{{ val }}</option>
                    {% endfor %}
                </select>
                {% endif %}
            </div>
        </div>
        {% endfor %}

        <div class="form-group">
            <div>
                <button type="submit" class="btn btn-primary">提交留言</button>
                <button type="reset" class="btn btn-secondary">重置</button>
            </div>
        </div>
</form>

This code is first wrapped in a<form>Its label,actionproperty points to/guestbook.htmlThis is the default message submission interface for AnQiCMS. Inside the loop, we render the corresponding HTML form elements for differentitem.TypeRendering the corresponding HTML form element. For example,textandnumberType, rendering<input>Label; fortextarea, rendering<textarea>; for selecting type (radio/checkbox/select), will further loopitem.ItemsGenerate options.item.RequiredThe attribute is used to dynamically add HTML.requiredAttribute to implement client-side required validation.

Submission and data processing of the message form.

When the user fills in and submits the form, the data will be sent to/guestbook.html. In addition to the above dynamically generated custom fields, AnQiCMS also requires submission of several fixed core fields:

  • user_name: The name of the user who leaves a message, this field is required.
  • contact: The contact information of the user, such as phone number, landline, WeChat ID, QQ number, etc., this field is also required.
  • content: The specific content of the message, this field is also required.
  • Other custom field: According to the backend configuration, these fields may be required or optional.
  • return(Optional): Used to specify the format of the backend returned data. If the value ishtml(Default), the backend may return an HTML page; if the value isjson, the backend will return data in JSON format, which is very useful when performing AJAX submissions.

To better control the form structure, you can also not rely on it completelyguestbookLabel the loop output, rather than manually constructing a form, only dynamically rendering for the extra fields customized by the backend. For example, you can hard codeuser_name/contactandcontentfields, then only loop renderguestbookFields provided by the label.

Enhance security by combining captcha.

To prevent malicious submissions and spam, the comment form usually needs to integrate captcha functionality. AnQiCMS throughtag-/anqiapi-other/167.htmlThe document provides a method to enable captcha in comments or replies.

First, make sure in the AnQiCMS background.Global settings -> Content settingsMarkdown editor is enabled (although the document describes the Markdown editor, the captcha feature is mentioned here, which may be a cross-reference in document writing, usually the captcha settings will be in a separate "captcha settings" or "security settings").

Then, in your comment form, you need to add two hidden fields and one for displaying the captcha image.<img>Label, and cooperate with JavaScript to dynamically obtain and refresh the captcha:

<div class="form-group captcha-group">
    <label for="captcha">验证码{% if item.Required %}<span class="text-danger">*</span>{% endif %}</label>
    <div style="display: flex; align-items: center;">
        <input type="hidden" name="captcha_id" id="captcha_id">
        <input type="text" name="captcha" required placeholder="请填写验证码" class="form-control" style="flex: 1; margin-right: 10px;">
        <img src="" id="get-captcha" style="width: 150px; height: 40px; cursor: pointer; border: 1px solid #ccc;" alt="验证码" />
    </div>
</div>

<script>
    // 使用原生JS获取和刷新验证码
    document.getElementById('get-captcha').addEventListener("click", function (e) {
        fetch('/api/captcha')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                return response.json();
            })
            .then(res => {
                if (res.code === 0) {
                    document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id);
                    document.getElementById('get-captcha').setAttribute("src", res.data.captcha);
                } else {
                    console.error('获取验证码失败:', res.msg);
                    alert('获取验证码失败,请重试!');
                }
            })
            .catch(err => {
                console.error('获取验证码异常:', err);
                alert('获取验证码时发生错误,请检查网络或稍后再试。');
            });
    });
    // 页面加载后自动点击一次,获取初始验证码
    document.getElementById('get-captcha').click();
</script>

This code sends a request to the interface using JavaScript to/api/captchaobtain the captcha.captcha_idand imagesrcand fill it into the form and image elements. When the user clicks the captcha image, it triggers a refresh operation.

Summary

The process of rendering and handling the message form fields in AnQiCMS templates is a combination of backend configuration and frontend template dynamic rendering. ThroughguestbookLabel, we can flexibly obtain the form structure defined by the background;By means of conditional judgment and loops, we can transform these structures into fully functional HTML forms;And integrating the captcha mechanism further enhances the security of the form.Mastering these methods will help you provide users with an efficient, secure, and user-friendly comment interaction interface.


Frequently Asked Questions (FAQ)

Why did I render the comment form according to the document, but it did not succeed after submission?

Firstly, please check your formactionIs the property correctly pointed to/guestbook.html. Secondly, confirm whether you have included all required fields:user_name/contact/contentand all other fields marked as 'required' by the backend. If captcha is integrated, make surecaptcha_idandcaptchathe field is also submitted correctly andcaptcha_idthe value is from/api/captchaThe interface retrieves. Check the browser console network requests, view the submitted response information, usually you can find the specific error cause.

Can I submit the message form via AJAX instead of page redirection?

Yes, AnQiCMS supports AJAX submission. You need to add a hidden field in the form<input type="hidden" name="return" value="json">. When this field exists, the backend will return JSON formatted data (usually containingcodeandmsg). Front-end JavaScript can accessfetchorjQuery.ajaxSubmit form data in this way and process the returned JSON data accordingly, for example, display success or failure messages without page jumping.

How to customize the style of the comment form?

The style of the comment form is completely controlled by your frontend CSS.After rendering the HTML form elements in the template, you can apply custom styles to them like any other HTML element, using CSS selectors (such as class names, IDs, or element types).It is recommended to add a specific element outside the form elementdivorformLabel, and specify a unique class name or ID for it to control its style more accurately, to avoid style conflicts with other parts of the website.

Related articles

How to integrate and display comment lists in AnQiCMS templates?

Effectively integrating and displaying the comment list in AnQi CMS is crucial for enhancing website user interaction, activating community atmosphere, and obtaining valuable user feedback.As an experienced CMS website operation personnel of an enterprise, I know that high-quality content cannot be separated from the active participation of users.The Anqi CMS provides powerful and flexible template tags, allowing us to easily implement this feature on the front end of the website.### Overview of Comment Functionality and Template File Organization AnQi CMS has built-in comment management functionality, allowing website administrators to review, reply to, and manage user comments

2025-11-06

How to display the Tag list or document list of a specified Tag in AnQiCMS template?

As an experienced CMS website operation personnel of an enterprise, I fully understand the core value of content tags in website content management and user navigation.High-quality tag strategies not only help readers quickly find the information they need, but also effectively improve the organization and SEO performance of website content.Next, I will elaborate on how to flexibly use tags in AnQiCMS templates to display tag lists or document lists under specific tags.### Understand the content tags in AnQiCMS In AnQiCMS, content tags (Tags) are a powerful content association tool

2025-11-06

How to create a multi-condition filtering interface based on document parameters in the AnQiCMS template?

As an experienced security CMS website operator, I know that building an efficient, user-friendly content filtering interface is important for improving user experience and content discoverability.In AnQiCMS, with its flexible content model and powerful template tag system, we can easily create a multi-condition filtering interface based on document parameters.This not only helps readers quickly find the information they need, but also effectively improves the organization and SEO performance of the website content.### The Basics of Creating a Multi-Condition Filter Interface: Understanding Document Parameters In AnQiCMS

2025-11-06

How to call custom document extra parameters (such as article author, product price) in AnQiCMS templates?

In the daily operation of AnQiCMS, we often need to add some personalized information to different types of content (such as articles, products), such as the specific author of the article, the detailed price of the product, the production date, etc.AnQiCMS is a powerful content model feature that allows us to flexibly define these custom fields and conveniently call them and display them in templates, thereby meeting the diverse content display needs.

2025-11-06

How to display the friend link list of the website in AnQiCMS template?

As an experienced CMS website operation person in the security industry, I fully understand that in website operation, friendship links are not only an embodiment of external resource cooperation, but also an important aspect of SEO optimization and user experience construction.AnQiCMS has always been committed to providing simple and efficient solutions in content management and template integration, and displaying the friend link list is no exception.Now, I will introduce to you how to elegantly display the website's friend link list in the AnQiCMS template.In modern website operation

2025-11-06

How to generate a pagination navigation with page number control in AnQiCMS template?

Hello! As a senior CMS website operator, I fully understand the importance of high-quality content and user experience.Page navigation is an indispensable part of content-based websites, directly affecting the user's browsing experience and the discoverability of content.In AnQiCMS, generating a pagination navigation with page number control is an intuitive and powerful process. Below, I will elaborate on how to implement this feature in the AnQiCMS template.### In AnQiCMS template, generate pagination navigation with page number control In the content management system

2025-11-06

How to format a timestamp into a readable date and time in the AnQiCMS template?

As an experienced CMS website operation personnel of an enterprise, I know that every detail of user experience is crucial in content management.Clarity in presenting dates and times often directly affects readers' perception of the timeliness and professionalism of the content.Today, I will give a detailed explanation of how to convert those mysterious timestamps into the readable date and time format that we are accustomed to in the AnQiCMS template.

2025-11-06

How to declare and assign variables in AnQiCMS templates for subsequent use?

As an experienced security CMS website operator, I am well aware of the importance of template design for website content display and user experience.Using variables in templates is the key to customizing pages and improving development efficiency.Today, I will elaborate on how to declare and assign variables in the AnQiCMS template, so that you can build and manage your website content more effectively.

2025-11-06