How to call and display the form fields submitted by users in the AnQiCMS template?

Calendar 👁️ 62

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)

  1. 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.

  2. 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.

  3. except for HTML5'srequiredCan 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.

Related articles

How does AnQiCMS display the comment list on article or product detail pages?

In website operation, user interaction is an important link to enhance the value of content and the level of website activity.The comment function serves as a bridge for users to directly communicate with content, not only enriching the page content, but also bringing unique UGC (User Generated Content) to the website, enhancing the community atmosphere, and also positively affecting search engine optimization (SEO).AnQiCMS (AnQiCMS) provides a powerful and flexible comment list display feature, allowing you to easily display user comments on articles or product detail pages and manage them effectively.

2025-11-08

How to dynamically display the breadcrumb navigation of the current page in AnQiCMS template?

Build a user-friendly, SEO-friendly website in AnQiCMS, breadcrumb navigation is an indispensable element.It can clearly show the user's current location, help the user quickly backtrack, and provide valuable website structure information for search engines.AnQiCMS's powerful template engine provides a simple and efficient way to dynamically generate these navigation paths.AnQiCMS's template system adopts syntax similar to the Django template engine, which makes it very easy for content developers to control the display of page content through tags and variables

2025-11-08

How to build and display a multi-level website navigation menu in AnQiCMS?

In website operation, a clear and intuitive navigation menu is the core of user experience, it can not only guide visitors to quickly find the information they need, but is also an important part of website structure and SEO optimization.AnQiCMS as an efficient enterprise-level content management system, provides flexible and powerful navigation menu construction and display functions, helping you easily manage the hierarchical structure of your website.**One, build navigation menu in AnQiCMS background** The first step in building a multi-level navigation menu is to centrally manage it in the AnQiCMS background

2025-11-08

How to control the thumbnail size and cropping method in AnQiCMS template?

When building and operating a website, the presentation of images often directly affects user experience and the professionalism of the site.AnQiCMS (AnQiCMS) fully understands this and provides users with a powerful and flexible thumbnail control function, allowing you to precisely manage the display of images on the website front-end according to your actual needs.This article will introduce in detail how to achieve fine-grained control over the thumbnail size and cropping method of images in Anqi CMS through backend settings and template calls.### Backend sets thumbnail rules unification

2025-11-08

How to display the Tag list associated with the article in AnQiCMS?

In AnQiCMS, effectively managing and displaying the tag (Tag) list of articles can not only help with content organization but also significantly improve the internal link structure and search engine optimization (SEO) effect of the website.Labels as a flexible classification method can link articles across categories and themes, providing users with a richer browsing path. ### Manage and create article tags in the background First, understanding how to add and manage article tags in the AnQiCMS background is fundamental.

2025-11-08

How to retrieve and display the friend link list in AnQiCMS template?

In website operation, friendship links are an important factor in improving website authority, increasing external traffic, and optimizing user experience.AnQiCMS (AnQiCMS) is well aware of this, and therefore provides a convenient friend link management function in system design, and supports flexible calling and display in templates.This article will provide a detailed introduction on how to retrieve and display the friend link list in your AnQiCMS template.### Management of friendship links: Starting from the background Before starting the template call, make sure that your website's background has configured the friendship links

2025-11-08

How to display the document list under a specific Tag in AnQiCMS?

In AnQiCMS, tags (Tag) are a powerful and flexible way to organize content, allowing you to associate documents in multiple dimensions without relying on traditional hierarchical classification structures.When you want to display all documents under a specific topic or keyword, it is particularly important to show the document list under a specific tag.This not only helps visitors find the content they are interested in faster, but also effectively improves the internal link structure and SEO performance of the website.

2025-11-08

How to dynamically retrieve and display the contact information of the website in AnQiCMS?

In today's digital age, a website's contact information is more than just cold numbers or addresses; it is a bridge for users to build trust and communicate with the company.Efficiently and accurately display this information on the website, and be able to update it flexibly as needed, which is crucial for any website operator.AnQiCMS as an enterprise-level content management system provides a very intuitive and powerful solution in this aspect, allowing you to easily manage these key information without touching complex code.This article will introduce how to configure and dynamically obtain the contact information of the website in AnQiCMS

2025-11-08