Implementing an Activity Submission Form in WeChat Mini Programs
This article focuses on the core code implementation for an activity application page within a WeChat Mini Program, developed using native WeChat syntax and Tencent Cloud Development. The goal is to detail the technical aspects of building interactive forms, covering standard input fields, various selection mechanisms, and client-side validation before data submission.
1. Standard Input Fields
Many form elements, such as activity name, location, contact person details, estimated participant count, project description, and budget, are typical implemented using simple text input fields. The fundamental approach involves:
- WXML: Utilizing the
<input>component, configuring itstypeattribute for the appropriate keyboard, setting aplaceholdertext, and binding an input event handler withbindinput. - JavaScript: Declaring a corresponding data property in the component's
dataobject. Thebindinputfunction then updates this property usingthis.setData()with the user's input. The stored data is later retrieved for form submission.
Let's illustrate with an example for an "Activity Name" input:
<!-- WXML -->
<input type="text" placeholder="Activity Title (Required*)" class="form-input" bindinput="onActivityNameInput"/>
// JavaScript
// Handler for activity name input
onActivityNameInput(event) {
const activityTitle = event.detail.value;
console.log("Activity Title Input:", activityTitle);
this.setData({
activityTitleData: activityTitle // Store the input value in component data
});
console.log("Stored Activity Title:", this.data.activityTitleData);
},
When the entire form is submitted, the value stored in activityTitleData will be sent to the backend.
2. Selection Components
The activity application form often includes different types of selection components, such as dropdowns for predefined options and direct radio buttons for binary or multiple-choice selections.
2.1 Dropdown Selector (Picker)
Dropdown selectors are implemented using the <picker> component, which is suitable for selecting one item from a list. The core logic includes:
- WXML: Creating a
<picker>component, binding itsvalueto a data variable representing the selected index, and itsrangeto a data array containing the options. An event handlerbindchangeis set to capture selection changes. A<view>component typically displays the currently selected option. - JavaScript: Initializing an array of options and a default selected index in the component's
data. Thebindchangehandler updates the selected index and, subsequently, the actual value (e.g., text) associated with the selection.
Here's an example for selecting an "Event Campus":
<!-- WXML -->
<picker bindchange="onCampusChange" value="{ {selectedCampusIndex}}" range="{ {campusOptions}}">
<view class="picker-display-area">
Current Selection: { {campusOptions[selectedCampusIndex]}}
</view>
</picker>
// JavaScript
data: {
campusOptions: ['', 'Campus A', 'Campus B', 'Campus C'], // First element often left empty or as a placeholder
selectedCampusIndex: 0,
eventCampus: '', // Stores the selected campus name
},
// Handler for campus picker selection
onCampusChange: function(event) {
const newIndex = event.detail.value;
this.setData({
selectedCampusIndex: newIndex,
eventCampus: this.data.campusOptions[newIndex] // Directly assign the selected option's text
});
console.log('Selected Campus:', this.data.eventCampus);
},
2.2 Direct Radio Button Selector
Direct radio button selectors are used when choices are immediately visible and mutually exclusive. This section also covers conditionally displaying additional input fields based on a "Yes" selection.
- WXML: Using a
<radio-group>with abindchangehandler. Inside,<label>components are rendered usingwx:forover a data array. Each<label>contains a<radio>with itsvaluebound to the iterated item's value, and a<view>to display the item's name. A surrounding<view>with thehiddenattribute (orwx:if) can control the visibility of related sub-forms. - JavaScript: Defining an array of radio options in
data. Theradio-group's handler determines the selected option and updates a boolean variable usingthis.setData(). This boolean variable then controls thehiddenattribute, making associated input fields appear or disappear.
Example: "Is there sponsorship?" with conditional fields:
<!-- WXML -->
<view class="form-section">
<view class="form-label">Is there sponsorship? <text class="required-star">*</text></view>
<radio-group bindchange="onSponsorshipChange">
<label wx:for="{ {sponsorshipOptions}}" wx:key="val" class="radio-option">
<view><radio value="{ {item.val}}"/></view>
<view>{ {item.label}}</view>
</label>
</radio-group>
<!-- Conditional display of sponsorship details -->
<view hidden="{ {hideSponsorDetails}}">
<view class="form-label">Sponsorship Information <text class="required-star">*</text></view>
<input type="text" placeholder="Sponsor Company (Required)" class="form-input" bindinput="onCompanyInput"/>
<input type="text" placeholder="Sponsorship Type" class="form-input" bindinput="onFormInput"/>
<input type="number" placeholder="Sponsorship Amount (Required)" class="form-input" bindinput="onAmountInput"/>
<view class="form-label">Contract Submitted? <text class="required-star">*</text></view>
<radio-group bindchange="onContractSubmitChange">
<label wx:for="{ {contractStatusOptions}}" wx:key="val" class="radio-option">
<view><radio value="{ {item.val}}"/></view>
<view>{ {item.label}}</view>
</label>
</radio-group>
</view>
</view>
// JavaScript
data: {
sponsorshipOptions: [
{val: 'yesSponsor', label: 'Yes'},
{val: 'noSponsor', label: 'No'},
],
contractStatusOptions: [ /* ... options for contract status */ ],
hideSponsorDetails: true, // Initially hide sponsorship details
// ... other data fields for sponsor info
},
// Handler for sponsorship radio selection
onSponsorshipChange(event) {
const selectedValue = event.detail.value;
console.log('Sponsorship option selected:', selectedValue);
this.setData({
hideSponsorDetails: (selectedValue === "noSponsor") // Hide if "No" is selected
});
// ... potentially clear related sponsor data if "No" is selected
},
3. Date and Time Selection
For selecting specific dates or times, the <picker> component with appropriate mode attributes (e.g., mode="date", mode="time", mode="multiSelector") provides a user-friendly interface. The component handles the native UI integration, requiring minimal custom logic.
<!-- WXML -->
<picker mode="date" start="2023-01-01" end="2025-12-31" bindchange="onEventStartDateChange">
<view class="picker-display-area">
Event Start Date: { {eventStartDate}}
</view>
</picker>
// JavaScript
data: {
eventStartDate: 'Select Date',
},
// Handler for event start date selection
onEventStartDateChange(event) {
const selectedDate = event.detail.value;
this.setData({
eventStartDate: selectedDate
});
console.log("Activity Start Date:", selectedDate);
},
4. Submission Button and Validation Logic
While the submission button's WXML code is straightforward, the associated JavaScript function typically contains the most extensive logic. This is primarily due to the necessity of comprehensive client-side validation before transmitting data to the database.
A robust submission process involves:
- Pre-submission Validation: Checking if all mandatory fields are filled and if data formats are correct. For instance, if the "Activity Name" field is empty, a user alert should prevent submission.
- Data Structure and Status: When submitting to a database, it's common to include a status field. For an approval-based system, this field might store numerical values representing different states (e.g.,
0for "Pending Initial Review",1for "Approved",2for "Rejected",3for "Pending Re-review",4for "Completed"). This allows for tracking and managing the activity's lifecycle through various approval stages.
Here's a conceptual outline for a submission handler, highlighting validation:
// JavaScript
async submitActivityApplication() {
const { activityTitleData, eventCampus, sponsorCompany, ...otherFormData } = this.data;
// --- Validation Checks ---
if (!activityTitleData || activityTitleData.trim() === '') {
wx.showToast({ title: 'Please enter activity title', icon: 'none' });
return;
}
if (!eventCampus || eventCampus.trim() === '') {
wx.showToast({ title: 'Please select event campus', icon: 'none' });
return;
}
// Add more validation for other mandatory fields and formats
// Example: if sponsorship is 'yesSponsor' then sponsorCompany should not be empty
if (this.data.hideSponsorDetails === false && (!sponsorCompany || sponsorCompany.trim() === '')) {
wx.showToast({ title: 'Please enter sponsor company', icon: 'none' });
return;
}
// --- Prepare Data for Submission ---
const applicationData = {
activityTitle: activityTitleData,
campus: eventCampus,
// ... map other form data
submissionStatus: 0, // Initial status: Pending Initial Review
createdAt: new Date().getTime(),
// ... other relevant fields
};
try {
// --- Cloud Function Call (Example) ---
const res = await wx.cloud.callFunction({
name: 'submitApplication', // Your cloud function name
data: applicationData,
});
console.log('Application submitted successfully:', res);
wx.showToast({ title: 'Application submitted!', icon: 'success' });
// Navigate or clear form
} catch (err) {
console.error('Error submitting application:', err);
wx.showToast({ title: 'Submission failed', icon: 'error' });
}
},