### Importing UI Components and Client Modules Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/page.mdx This snippet imports essential modules for the page: `ExamplesClient` for handling dynamic examples and `Button` from a UI component library for interactive elements. ```TypeScript import { ExamplesClient } from "./examples-client"; import { Button } from "@/components/ui/button"; ``` -------------------------------- ### Rendering Kinlink Examples Page Structure Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/page.mdx This JSX snippet defines the main layout and content of the examples page. It includes a prominent title, a descriptive subtitle, embeds the `ExamplesClient` component, and provides call-to-action buttons for contacting support and viewing documentation. ```JSX

示例

浏览我们的示例集合,了解如何有效使用kinlink。

需要自定义示例?

找不到您需要的内容?我们的团队可以帮助您创建根据您特定需求定制的示例。
``` -------------------------------- ### GET Request Examples with kinlink.proxy (JavaScript) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/proxy/page.mdx This example demonstrates how to perform simple GET requests using `kinlink.proxy`. It shows fetching user data by ID and making a GET request with query parameters, both configured to accept JSON responses. The `kinlink.proxy` function handles the secure, server-side forwarding of these requests, bypassing CORS limitations. ```javascript // 简单的GET请求 const userData = await kinlink.proxy( 'https://api.example.com/users/123', 'GET', { 'Accept': 'application/json' } ); console.log('用户信息:', userData); // 带查询参数的GET请求 const searchResults = await kinlink.proxy( 'https://api.example.com/search?q=keyword&limit=10', 'GET', { 'Accept': 'application/json' } ); ``` -------------------------------- ### Defining Page Metadata for SEO Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/page.mdx This snippet exports a `metadata` object, which is used by frameworks like Next.js to set the page's title and description for browser tabs and search engine optimization (SEO). ```TypeScript export const metadata = { title: "示例 - kinlink开发者", description: "浏览我们的示例集合,了解如何有效使用kinlink。", }; ``` -------------------------------- ### POST Request Example with kinlink.proxy (JavaScript) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/proxy/page.mdx This example illustrates how to make a POST request using `kinlink.proxy` to create a new user resource. It specifies `Content-Type` and `Accept` headers for JSON, and includes a JSON body with user details. The `kinlink.proxy` handles the secure transmission of this data to the external API without exposing sensitive information on the frontend. ```javascript // 创建新用户 const newUser = await kinlink.proxy( 'https://api.example.com/users', 'POST', { 'Content-Type': 'application/json', 'Accept': 'application/json' }, { name: '张三', email: 'zhangsan@example.com', department: '技术部' } ); console.log('创建的用户:', newUser); ``` -------------------------------- ### DELETE Request Example with kinlink.proxy (JavaScript) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/proxy/page.mdx This example illustrates how to perform a DELETE request using `kinlink.proxy` to remove a user resource from an external system. After the successful deletion, it uses `kinlink.formApi.showSuccess` to display a confirmation message to the user, demonstrating a complete interaction flow for resource removal. ```javascript // 删除用户 await kinlink.proxy( 'https://api.example.com/users/123', 'DELETE', { 'Accept': 'application/json' } ); kinlink.formApi.showSuccess('用户删除成功'); ``` -------------------------------- ### Demonstrating Message Notifications with Kinlink Form API (JavaScript) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/message-notification/page.mdx This JavaScript snippet showcases how to use the `kinlink.formApi` to display different types of messages (success, error, info, warning) and messages with custom display durations. It dynamically creates a control panel on the form load event, allowing users to interactively test the message functionalities, including clearing all active messages. It depends on the `kinlink` global object and its `formApi`. ```JavaScript /** * 示例10: 消息提示演示 * 功能:展示各类消息提示功能 */ (function () { kinlink.events.on(kinlink.FormEvents.FORM_LOADED, () => { try { // 创建消息演示控制面板 const demoPanel = document.createElement('div'); demoPanel.style.margin = '15px 0'; demoPanel.style.padding = '15px'; demoPanel.style.backgroundColor = '#f8f9fa'; demoPanel.style.border = '1px solid #dee2e6'; demoPanel.style.borderRadius = '8px'; // 标题 const title = document.createElement('h3'); title.textContent = '消息提示演示'; title.style.marginTop = '0'; title.style.marginBottom = '15px'; demoPanel.appendChild(title); // 消息类型数组 const messageTypes = [ { type: 'success', label: '成功消息', color: '#27ae60' }, { type: 'error', label: '错误消息', color: '#e74c3c' }, { type: 'info', label: '信息提示', color: '#3498db' }, { type: 'warning', label: '警告消息', color: '#f39c12' } ]; // 为每种消息类型创建按钮 messageTypes.forEach((item) => { const button = document.createElement('button'); button.type = 'button'; button.textContent = item.label; button.style.marginRight = '10px'; button.style.marginBottom = '10px'; button.style.padding = '8px 16px'; button.style.backgroundColor = item.color; button.style.color = 'white'; button.style.border = 'none'; button.style.borderRadius = '4px'; button.style.cursor = 'pointer'; // 点击按钮显示对应类型的消息 button.addEventListener('click', () => { const message = '这是一条' + item.label + '(' + new Date().toLocaleTimeString() + ')'; // 根据消息类型调用不同的方法 switch (item.type) { case 'success': kinlink.formApi.showSuccess(message); break; case 'error': kinlink.formApi.showError(message); break; case 'info': kinlink.formApi.showInfo(message); break; case 'warning': kinlink.formApi.showWarning(message); break; default: // 使用通用方法 kinlink.formApi.showMessage(item.type, message); } }); demoPanel.appendChild(button); }); // 创建持续时间控制 const durationControl = document.createElement('div'); durationControl.style.marginTop = '15px'; const durationLabel = document.createElement('label'); durationLabel.textContent = '显示时间(秒): '; durationControl.appendChild(durationLabel); const durationInput = document.createElement('input'); durationInput.type = 'number'; durationInput.min = '1'; durationInput.max = '10'; durationInput.value = '3'; durationInput.style.width = '50px'; durationInput.style.marginRight = '15px'; durationControl.appendChild(durationInput); // 创建自定义消息按钮 const customButton = document.createElement('button'); customButton.type = 'button'; customButton.textContent = '显示自定义时长消息'; customButton.style.padding = '8px 16px'; customButton.style.backgroundColor = '#9b59b6'; customButton.style.color = 'white'; customButton.style.border = 'none'; customButton.style.borderRadius = '4px'; customButton.style.cursor = 'pointer'; customButton.addEventListener('click', () => { const duration = parseInt(durationInput.value, 10); const message = '此消息将显示' + duration + '秒钟'; kinlink.formApi.showInfo(message, duration); }); durationControl.appendChild(customButton); demoPanel.appendChild(durationControl); // 创建清除所有消息的按钮 const clearButton = document.createElement('button'); clearButton.type = 'button'; clearButton.textContent = '清除所有消息'; clearButton.style.marginTop = '15px'; clearButton.style.padding = '8px 16px'; clearButton.style.backgroundColor = '#7f8c8d'; clearButton.style.color = 'white'; clearButton.style.border = 'none'; clearButton.style.borderRadius = '4px'; clearButton.style.cursor = 'pointer'; clearButton.addEventListener('click', () => { kinlink.formApi.clearAllMessages(); }); demoPanel.appendChild(clearButton); // 将演示面板添加到页面 const formElement = document.querySelector('.ant-form') || document.body; formElement.insertBefore(demoPanel, formElement.firstChild); } catch (error) { console.error('初始化消息提示演示失败:', error); } }); })(); ``` -------------------------------- ### Defining Multi-Step Form Configuration - JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/multi-step-form/page.mdx This JavaScript snippet defines the configuration for a multi-step form, specifying each step's title, an associated icon, and a list of form fields belonging to that step. This structure guides the form's flow and content. ```JavaScript // 步骤配置 const steps = [ { title: '基本信息', icon: '📋', fields: [ '文字列__1行__0', '文字列__1行__1', '单行文本框_8', '单行文本框_9', '单选框_0', '日期_1', '多选_0', '表格', ``` -------------------------------- ### Implementing Responsive Form Layout - Kinlink Layout API - JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/layout-api/page.mdx Demonstrates how to create a responsive form layout using the Kinlink Layout API. It checks for mobile devices to apply specific optimizations like hiding the header and showing the mobile action bar, while desktop layouts ensure header/footer visibility and listen for general layout changes. This example initializes on the FORM_LOADED event. ```javascript (function() { kinlink.events.on(kinlink.FormEvents.FORM_LOADED, () => { const isMobile = kinlink.layoutApi.checkIsMobileDevice(); if (isMobile) { // 移动布局优化 // 隐藏页眉以节省空间 kinlink.layoutApi.hideHeader(); // 确保移动操作栏可见 kinlink.layoutApi.mobileShowFormActionBar(); // 监听方向变化 window.addEventListener('resize', () => { const contentHeight = kinlink.layoutApi.getContentAreaHeight(); console.log('调整大小后的内容高度:', contentHeight); // 根据需要调整布局 // ... }); } else { // 桌面布局 // 显示页眉和页脚 kinlink.layoutApi.showHeader(); kinlink.layoutApi.showFooter(); // 监听布局变化 kinlink.layoutApi.onLayoutChange((detail) => { console.log('布局元素已变化:', detail); // 根据需要调整布局 // ... }); } console.log('响应式布局已初始化'); }); })(); ``` -------------------------------- ### Defining kinlink.proxy Method Signature in JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/apiDocs/kinlink-ai-agent.md This snippet provides the method signature for `kinlink.proxy`, which enables secure HTTP requests to external systems from custom scripts. It outlines the parameters required for the proxy call: `url`, `method`, `headers`, and `body`, and indicates it returns a Promise. ```javascript await kinlink.proxy(url, method, headers, body) ``` -------------------------------- ### Integrating with External Systems via API in JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/apiDocs/kinlink-ai-agent.md This snippet shows how to integrate with an external system by fetching user data based on a '用户ID' field change. It uses an `async` function to call an external API (represented by `fetchUserData`), displays loading/error messages, and populates form fields with the retrieved data. Error handling is included with a `try-catch` block. ```javascript (function() { kinlink.events.on(kinlink.FormEvents.FIELD_CHANGE, async (data) => { const { fieldName, value } = data; if (fieldName === '用户ID' && value) { try { const form = kinlink.formApi; form.showInfo('正在获取数据...'); // 调用外部API const userData = await fetchUserData(value); // 实现此函数 // 填充表单 form.setFieldValue('用户名', userData.name); form.setFieldValue('邮箱', userData.email); } catch (error) { kinlink.formApi.showError('获取数据失败'); } } }); })(); ``` -------------------------------- ### Getting Field Values in JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/guides/field-operations/page.mdx This snippet demonstrates how to retrieve data from form fields using the `kinlink.formApi`. It shows how to get the value of a single field by its name using `getFieldValue()` and how to fetch all form values as an object using `getAllValues()`. These methods are essential for conditional logic, data validation, and preparing data for submission. ```javascript // 获取单个字段的值 const name = kinlink.formApi.getFieldValue('name'); console.log(name); // 输出: "John Doe" // 获取所有表单值 const allValues = kinlink.formApi.getAllValues(); console.log(allValues); // 输出: { name: "John Doe", email: "john@example.com", ... } ``` -------------------------------- ### Overview of kinlink Core JavaScript API Structure Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/llm.txt This snippet illustrates the global `window.kinlink` object, which serves as the entry point for all kinlink JavaScript APIs. It exposes various modules like `formApi` for field operations and validation, `layoutApi` for UI control, `events` for event handling, `FormEvents` for predefined event types, and a `proxy` service for secure external API calls. This structure provides a comprehensive interface for interacting with and extending Kintone applications. ```javascript window.kinlink = { // Form Operations API formApi: { getFieldValue, setFieldValue, getAllValues, setFieldsValue, hideField, showField, visuallyHideField, getFieldState, disableField, enableField, addFieldValidator, removeFieldValidator, validateField, validateForm, setFieldError, clearFieldError, setFieldsErrors }, // Layout Control API layoutApi: { getHeaderHeight, isHeaderVisible, hideHeader, showHeader, getFooterHeight, isFooterVisible, hideFooter, showFooter, isSubmitButtonVisible, hideSubmitButton, showSubmitButton }, // Event System events: { on, off }, // Event Types FormEvents: { FORM_LOADED, FIELD_CHANGE, BEFORE_SUBMIT, AFTER_SUBMIT }, // Proxy Service proxy: (url, method, headers, body) => Promise } ``` -------------------------------- ### Implementing Asynchronous Validation with Kinlink JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/guides/form-validation/page.mdx This example illustrates how to perform asynchronous validation, such as checking username availability, using Kinlink's event system. It includes debouncing to prevent excessive API calls and manually sets/clears field errors based on the asynchronous result. ```javascript // 示例:在字段更改时进行异步用户名可用性检查 let debounceTimer; kinlink.events.on(kinlink.FormEvents.FIELD_CHANGE, (data) => { if (data.fieldName === 'username') { clearTimeout(debounceTimer); debounceTimer = setTimeout(async () => { const username = data.value; if (!username) { kinlink.formApi.clearFieldError('username'); return; } try { // 假设 checkUsernameAvailability 是一个返回Promise的函数 // const isAvailable = await checkUsernameAvailability(username); // 模拟API调用 const isAvailable = await new Promise(resolve => setTimeout(() => resolve(!['admin', 'test'].includes(username)), 500)); if (!isAvailable) { kinlink.formApi.setFieldError('username', '此用户名已被使用'); } else { kinlink.formApi.clearFieldError('username'); } } catch (error) { kinlink.formApi.setFieldError('username', '检查用户名时出错'); console.error('异步验证错误:', error); } }, 300); // 防抖处理 } }); ``` -------------------------------- ### Integrating SSO for User Information Pre-fill (JavaScript) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/proxy/page.mdx This JavaScript example illustrates how to integrate Single Sign-On (SSO) to fetch user information and pre-fill form fields using `kinlink.proxy`. The `initializeUserFromSSO` function retrieves current SSO user data and uses `kinlink.formApi.setFieldsValue` to populate the form, disabling fields that users shouldn't modify. It runs on `DOMContentLoaded`. ```javascript // SSO用户信息获取和表单预填充 async function initializeUserFromSSO() { try { // 获取当前SSO用户信息 const userInfo = await kinlink.proxy( 'https://sso.company.com/api/user/current', 'GET', { 'Accept': 'application/json' } ); if (userInfo) { // 预填充用户信息 kinlink.formApi.setFieldsValue({ employeeId: userInfo.employeeId, fullName: userInfo.fullName, email: userInfo.email, department: userInfo.department, manager: userInfo.managerName }); // 隐藏用户自己无法修改的字段 kinlink.formApi.disableField('employeeId'); kinlink.formApi.disableField('email'); kinlink.formApi.showInfo('已自动填入您的基本信息'); } } catch (error) { kinlink.formApi.showError('无法获取用户信息,请手动填写'); } } // 页面加载时初始化 document.addEventListener('DOMContentLoaded', initializeUserFromSSO); ``` -------------------------------- ### Getting All Form Values - kinlink.formApi - JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/form-api/page.mdx This snippet demonstrates how to retrieve all field values from the form at once using `kinlink.formApi.getAllValues()`. It returns an object where keys are field codes and values are their corresponding data. This is useful for submitting or processing entire form data. ```javascript // 获取所有表单数据 const formData = kinlink.formApi.getAllValues(); console.log(formData); // 输出: { // name: "张三", // email: "zhang@example.com", // age: 30, // department: "技术部" // } ``` -------------------------------- ### Optimizing Form Layout for Mobile Devices in JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/apiDocs/kinlink-ai-agent.md This snippet demonstrates mobile adaptation logic executed on `FORM_LOADED`. It checks for mobile devices and simplifies the layout by hiding secondary information fields and adjusting the style of a primary field ('姓名') for better touch interaction, providing a distinct experience from the PC layout. ```javascript (function() { kinlink.events.on(kinlink.FormEvents.FORM_LOADED, () => { if (kinlink.layoutApi.checkIsMobileDevice()) { // 移动端布局简化 const form = kinlink.formApi; ['次要信息1', '次要信息2'].forEach(field => form.hideField(field)); // 更大触控区域 form.setFieldComponentStyle('姓名', { fontSize: '16px', padding: '12px 8px' }); } else { // PC端完整布局 } }); })(); ``` -------------------------------- ### PUT and PATCH Request Examples with kinlink.proxy (JavaScript) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/proxy/page.mdx This snippet demonstrates how to perform both PUT and PATCH requests using `kinlink.proxy` for updating resources. It shows a full update (PUT) of user information and a partial update (PATCH) of a user's status, both sending JSON bodies. These methods are used for modifying existing resources on external APIs securely. ```javascript // 更新用户信息(PUT) const updatedUser = await kinlink.proxy( 'https://api.example.com/users/123', 'PUT', { 'Content-Type': 'application/json' }, { name: '李四', email: 'lisi@example.com', status: 'active' } ); // 部分更新(PATCH) const patchedUser = await kinlink.proxy( 'https://api.example.com/users/123', 'PATCH', { 'Content-Type': 'application/json' }, { status: 'inactive' } ); ``` -------------------------------- ### Handling Form Submission After Submit in JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/apiDocs/kinlink-ai-agent.md This snippet shows how to register an event listener for the `AFTER_SUBMIT` event. It enables developers to execute custom business logic after a form has been submitted, such as processing server responses or updating UI based on submission success. ```javascript kinlink.events.on(kinlink.FormEvents.AFTER_SUBMIT, (data) => { const { result, success } = data; // result: 服务器响应结果 // success: 提交是否成功 }); ``` -------------------------------- ### Defining Form Structure for Dynamic Field Interactions - HTML Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/field-linking/page.mdx This HTML snippet outlines a basic form structure intended for dynamic field linkage. It includes fields for product type, quantity, price, and a read-only total, illustrating how form elements are organized with `data-field` attributes to facilitate interaction with JavaScript logic, enabling features like conditional visibility and automatic calculations. ```html
``` -------------------------------- ### Setting Field Values in JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/guides/field-operations/page.mdx This snippet illustrates how to programmatically set values for form fields using `kinlink.formApi`. It covers setting a single field's value with `setFieldValue()` and updating multiple fields simultaneously with `setFieldsValue()`. These functions are crucial for form initialization, pre-filling data, and responding to user actions or calculations. ```javascript // 设置单个字段的值 kinlink.formApi.setFieldValue('name', 'Jane Smith'); // 一次设置多个字段值 kinlink.formApi.setFieldsValue({ name: 'Jane Smith', email: 'jane@example.com', age: 30 }); ``` -------------------------------- ### Handling Form Submission Before Submit in JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/apiDocs/kinlink-ai-agent.md This snippet demonstrates how to register an event listener for the `BEFORE_SUBMIT` event. It allows developers to implement custom business logic before a form is submitted, such as modifying submission data or preventing submission based on validation. Returning `false` prevents the submission, while `true` allows it. ```javascript kinlink.events.on(kinlink.FormEvents.BEFORE_SUBMIT, (data) => { const { values } = data; // values: 提交数据对象的引用,可直接修改 // 返回false阻止提交,返回true允许提交 return true/false; }); ``` -------------------------------- ### Kinlink Backend Proxy URL Mapping Configuration (JSON) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/proxy/page.mdx This JSON configuration snippet provides an example of how to set up URL mappings for Kinlink's backend proxy service. It defines multiple `proxyConfigs` entries, each specifying a `name`, `urlPattern`, `authType` (e.g., bearer, apikey, custom), `authToken` or `authHeaders`, and optional settings like `rateLimiting`, `allowedMethods`, and `ipWhitelist`. Environment variables are used for sensitive tokens. ```json // kinlink后台配置示例(JSON格式) { "proxyConfigs": [ { "name": "HR系统API", "urlPattern": "https://hr.company.com/api/*", "enabled": true, "authType": "bearer", "authToken": "${process.env.HR_API_TOKEN}", "rateLimiting": { "requestsPerMinute": 60, "burstLimit": 10 } }, { "name": "CRM系统API", "urlPattern": "https://crm.company.com/api/*", "enabled": true, "authType": "apikey", "authHeaders": { "X-API-Key": "${process.env.CRM_API_KEY}", "X-Client-ID": "kinlink-integration" } }, { "name": "财务系统API", "urlPattern": "https://finance.company.com/api/*", "enabled": true, "authType": "custom", "authHeaders": { "Authorization": "Custom ${process.env.FINANCE_TOKEN}", "X-Request-Source": "kinlink" }, "allowedMethods": ["GET", "POST"], "ipWhitelist": ["10.0.0.0/8"] } ] } ``` -------------------------------- ### Environment Variable Configuration for Proxy Service (.env) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/proxy/page.mdx This snippet shows an example `.env` file for configuring environment variables used by the Kinlink proxy service. It includes placeholders for API tokens (HR, CRM, Finance), CRM secret, and general proxy settings like `PROXY_TIMEOUT`, `PROXY_MAX_REDIRECTS`, `PROXY_SSL_VERIFY`, and logging configurations (`LOG_LEVEL`, `LOG_PROXY_REQUESTS`). These variables are referenced in the JSON proxy configuration. ```bash # .env 配置文件示例 # HR系统认证 HR_API_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... # CRM系统认证 CRM_API_KEY=pk_live_1234567890abcdef CRM_SECRET=sk_live_0987654321fedcba # 财务系统认证 FINANCE_TOKEN=ft_abc123def456ghi789 # 代理服务配置 PROXY_TIMEOUT=30000 PROXY_MAX_REDIRECTS=5 PROXY_SSL_VERIFY=true # 日志配置 LOG_LEVEL=info LOG_PROXY_REQUESTS=true ``` -------------------------------- ### Implementing Real-time Field Calculations in JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/guides/field-operations/page.mdx This snippet demonstrates how to perform dynamic calculations based on field changes using `kinlink.events.on()`. It listens for `FIELD_CHANGE` events and recalculates a 'total' field whenever 'quantity' or 'price' fields are updated. This pattern is useful for providing immediate feedback to users, such as calculating order totals or tax amounts. ```javascript kinlink.events.on(kinlink.FormEvents.FIELD_CHANGE, (data) => { const { fieldName } = data; const form = kinlink.formApi; // 当数量或价格变化时重新计算总额 if (fieldName === 'quantity' || fieldName === 'price') { const quantity = Number(form.getFieldValue('quantity')) || 0; const price = Number(form.getFieldValue('price')) || 0; const total = quantity * price; form.setFieldValue('total', total); } }); ``` -------------------------------- ### Kinlink Form Event Data Structures (JavaScript) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/form-submission/page.mdx This snippet illustrates the data structures passed to `BEFORE_SUBMIT` and `AFTER_SUBMIT` event handlers in Kinlink. The `BEFORE_SUBMIT` event provides current form field values and the DOM element, while `AFTER_SUBMIT` provides submission success status, result data, and optional error messages. ```javascript // BEFORE_SUBMIT 事件数据 { values: { fieldCode: value, ... }, // 表单字段值 formElement: HTMLElement // 表单DOM元素 } // AFTER_SUBMIT 事件数据 { success: boolean, // 提交是否成功 result: any, // 提交结果数据 error?: string // 错误信息(如有) } ``` -------------------------------- ### Implementing Dynamic Field Linkage with Kinlink API - JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/field-linking/page.mdx This JavaScript code demonstrates how to create dynamic field interactions within a form using the `kinlink` API. It initializes field states on form load and listens for `FIELD_CHANGE` events to trigger updates, such as modifying field label styles based on gender selection or displaying informational messages based on a meeting place selection. This ensures real-time responsiveness and conditional UI adjustments. ```javascript /** * 示例7: 字段联动 * 功能:根据某个字段的值变化自动控制其他字段的状态 */ (function () { // 表单加载时的初始设置 kinlink.events.on(kinlink.FormEvents.FORM_LOADED, () => { try { // 性别字段联动初始化 updateFieldsByGender(kinlink.formApi.getFieldValue('单选框_0')); } catch (error) { console.error('字段联动初始化失败:', error); } }); // 监听字段变化事件 kinlink.events.on(kinlink.FormEvents.FIELD_CHANGE, (data) => { try { const { fieldName, value } = data; // 根据性别字段变化联动其他字段 if (fieldName === '单选框_0') { updateFieldsByGender(value); } // 根据集合场所的选择联动其他信息 if (fieldName === '下拉菜单') { updateByMeetingPlace(value); } // 联动设置案件编号与案件名称 if (fieldName === 'Lookup_0' && value) { // 假设这里会自动通过Lookup功能填充关联字段 // 如果没有自动填充,可以手动设置相关值 console.log('案件编号已更新:', value); } } catch (error) { console.error('字段联动处理失败:', error); } }); // 性别联动函数 function updateFieldsByGender(gender) { const form = kinlink.formApi; if (gender === '男') { // 对于男性,修改标签样式 form.setFieldLabelStyle('单行文本框_8', { color: '#3498db' }); form.setFieldLabelStyle('单行文本框_9', { color: '#3498db' }); } else if (gender === '女') { // 对于女性,修改标签样式 form.setFieldLabelStyle('单行文本框_8', { color: '#e74c3c' }); form.setFieldLabelStyle('单行文本框_9', { color: '#e74c3c' }); } // 可以在这里添加其他基于性别的联动逻辑 console.log('性别联动已处理:', gender); } // 集合场所联动函数 function updateByMeetingPlace(place) { const form = kinlink.formApi; // 根据不同集合场所设置不同信息 if (place === 'A') { form.showInfo('A场所的集合时间为上午9:00'); // 显示A场所特定字段(如果有) // form.showField('A场所注意事项'); } else if (place === 'B') { form.showInfo('B场所的集合时间为上午10:30'); // 显示B场所特定字段(如果有) // form.showField('B场所注意事项'); } console.log('集合场所联动已处理:', place); } })(); ``` -------------------------------- ### Sending Data to Kintone API via Kinlink Proxy (JavaScript) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/form-submission/page.mdx This JavaScript snippet demonstrates how to use `kinlink.proxy` within a form's `BEFORE_SUBMIT` event handler to send data to an external Kintone API. It performs a POST request to create a record, logs the response, and then returns `true` to allow form submission to proceed or `false` to prevent it if an error occurs. ```javascript // 使用kinlink.proxy发送数据到kintone API const res = await kinlink.proxy( 'https://pokemon36.cybozu.cn/k/v1/record.json', 'POST', { 'Content-Type': 'application/json' }, { app: 187, record: { 单行文本框: { value: 'kinlink' }, }, }, ); console.log(res, 'res'); // 返回true允许表单继续提交 return true; } catch (error) { console.error('表单提交前处理失败:', error); // 返回false阻止表单提交 return false; } }); })(); ``` -------------------------------- ### Form Validation Before Submission using kinlink.proxy (JavaScript) Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/proxy/page.mdx This example demonstrates how to integrate `kinlink.proxy` for external data validation before a form submission. It uses `kinlink.events.on(kinlink.FormEvents.BEFORE_SUBMIT)` to intercept the submission, securely call an external API via the proxy, and conditionally prevent form submission based on the API's response or any encountered errors. ```javascript kinlink.events.on(kinlink.FormEvents.BEFORE_SUBMIT, async (data) => { try { const { values } = data; // 通过代理安全调用外部API const result = await kinlink.proxy( 'https://api.example.com/endpoint', 'POST', { 'Content-Type': 'application/json' }, { foo: 'bar', ...values } ); // 可根据result决定是否允许提交 if (!result.success) { kinlink.formApi.showError('外部系统校验失败'); return false; // 阻止表单提交 } } catch (error) { kinlink.formApi.showError('外部系统请求失败'); return false; // 阻止表单提交 } }); ``` -------------------------------- ### Registering Event Listeners with kinlink.events.on - JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/api-reference/events/page.mdx This snippet demonstrates how to register various form event listeners using `kinlink.events.on`. It shows examples for `FORM_LOADED` (for initialization), `FIELD_CHANGE` (for dynamic field interaction), and `BEFORE_SUBMIT` (for pre-submission validation). The `on` method takes an `eventName` (string, from `kinlink.FormEvents`) and a `callback` function, returning a listener ID (string) for later removal. This is applicable for form initialization, field linkage, data validation, and user interaction responses. ```javascript // 注册表单加载事件 const loadListenerId = kinlink.events.on(kinlink.FormEvents.FORM_LOADED, () => { console.log('表单已完全加载,可以开始初始化'); // 执行表单初始化逻辑 initializeFormDefaults(); }); // 注册字段变化事件 const changeListenerId = kinlink.events.on(kinlink.FormEvents.FIELD_CHANGE, (data) => { console.log('字段发生变化:', data.fieldName, '新值:', data.value); // 实现动态响应逻辑 handleFieldInteraction(data); }); // 注册提交前事件 const beforeSubmitId = kinlink.events.on(kinlink.FormEvents.BEFORE_SUBMIT, (data) => { return validateBeforeSubmit(data.values); }); ``` -------------------------------- ### Controlling Field Visibility with kinlink API - JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/field-visibility-control/page.mdx This snippet demonstrates how to control the display and hidden states of form fields using the kinlink API. It shows how to completely hide a field (value not submitted), visually hide a field (value still submitted), and dynamically toggle the visibility of a table field using a custom button. It relies on `kinlink.events.on(kinlink.FormEvents.FORM_LOADED)` to ensure the form is ready. ```javascript /** * 示例3: 字段显示/隐藏控制 * 功能:控制表单字段的显示和隐藏状态 */ (function () { kinlink.events.on(kinlink.FormEvents.FORM_LOADED, () => { try { // 完全隐藏字段(值不会被提交) kinlink.formApi.hideField('多选_0'); // 仅视觉上隐藏字段(值仍会被提交) kinlink.formApi.visuallyHideField('选择组织'); // 通过按钮控制显示/隐藏同行者表格 const toggleButton = document.createElement('button'); toggleButton.type = 'button'; toggleButton.textContent = '显示/隐藏同行者信息'; toggleButton.style.margin = '10px 0'; toggleButton.style.padding = '5px 10px'; // 获取表单元素并添加按钮 const formElement = document.querySelector('.ant-form') || document.body; formElement.insertBefore(toggleButton, formElement.firstChild); // 初始隐藏同行者表格 kinlink.formApi.hideField('表格_13'); let isVisible = false; // 设置点击事件切换显示状态 toggleButton.addEventListener('click', () => { if (isVisible) { kinlink.formApi.hideField('表格_13'); toggleButton.textContent = '显示同行者信息'; } else { kinlink.formApi.showField('表格_13'); toggleButton.textContent = '隐藏同行者信息'; } isVisible = !isVisible; }); } catch (error) { console.error('控制字段显示/隐藏失败:', error); } }); })(); ``` -------------------------------- ### Optimizing Kinlink Forms for Mobile and Desktop Devices - JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/examples/mobile-adaptation/page.mdx This JavaScript snippet demonstrates how to adapt Kinlink forms based on the user's device type (mobile or desktop). It uses `kinlink.layoutApi.checkIsMobileDevice()` to detect the device and applies specific UI and interaction optimizations, such as hiding complex fields and enlarging touch areas for mobile, or displaying full features for desktop. It also adds a visual indicator for the detected device mode. ```javascript /** * 示例8: 移动端适配 * 功能:根据设备类型提供不同的UI和交互体验 */ (function () { kinlink.events.on(kinlink.FormEvents.FORM_LOADED, () => { try { // 检测是否是移动端设备 const isMobile = kinlink.layoutApi.checkIsMobileDevice(); console.log('是否移动端:', isMobile); if (isMobile) { // === 移动端优化 === applyMobileOptimization(); } else { // === PC端优化 === applyDesktopOptimization(); } // 添加状态指示器 addDeviceIndicator(isMobile); } catch (error) { console.error('移动端适配失败:', error); } }); // 移动端优化函数 function applyMobileOptimization() { const form = kinlink.formApi; // 隐藏复杂的同行者表格,简化移动端体验 form.hideField('表格_13'); // 增大触控区域,提高易用性 const fieldsToEnlarge = [ '文字列__1行__0', '文字列__1行__1', '单行文本框_8', '单行文本框_9', '文字列__1行__2', '文字列__1行__3' ]; fieldsToEnlarge.forEach((field) => { form.setFieldComponentStyle(field, { fontSize: '16px', padding: '12px 8px', borderRadius: '8px', marginBottom: '16px' }); }); // 避免使用多列布局 document.querySelectorAll('.ant-row').forEach((row) => { row.style.flexDirection = 'column'; }); // 修改提交按钮样式 const submitButtonStyles = { width: '100%', height: '44px', fontSize: '16px', borderRadius: '8px' }; // 假设有一个辅助函数来设置按钮样式(实际实现可能不同) const submitButton = document.querySelector( '#kinlink-mobile-submit-button' ); if (submitButton) { Object.assign(submitButton.style, submitButtonStyles); } // 显示定制的移动端消息 form.showInfo('正在使用移动端视图'); } // PC端优化函数 function applyDesktopOptimization() { // 使用更高级的表单布局 // 显示所有高级功能 // 显示定制的桌面端消息 kinlink.formApi.showInfo('正在使用桌面端视图'); } // 添加设备类型指示器 function addDeviceIndicator(isMobile) { const indicator = document.createElement('div'); // 设置样式 Object.assign(indicator.style, { position: 'fixed', top: '10px', right: '10px', padding: '5px 10px', backgroundColor: isMobile ? '#3498db' : '#27ae60', color: 'white', borderRadius: '4px', fontSize: '12px', zIndex: '1000' }); indicator.textContent = isMobile ? '移动端模式' : '桌面端模式'; document.body.appendChild(indicator); } })(); ``` -------------------------------- ### Implementing Conditional Field Display in JavaScript Source: https://github.com/gusanle/v0-kinlink-developer-guide/blob/main/app/docs/guides/field-operations/page.mdx This snippet demonstrates how to dynamically show or hide fields based on user input, creating an intelligent form experience. It uses `FORM_LOADED` to set initial hidden states and `FIELD_CHANGE` to listen for changes in a 'customerType' field. Depending on the selected customer type, it conditionally displays either 'businessName' or 'personalId' fields, enhancing user experience and form relevance. ```javascript kinlink.events.on(kinlink.FormEvents.FORM_LOADED, () => { // 初始隐藏字段 kinlink.formApi.hideField('businessName'); kinlink.formApi.hideField('personalId'); }); kinlink.events.on(kinlink.FormEvents.FIELD_CHANGE, (data) => { const { fieldName, value } = data; const form = kinlink.formApi; // 根据客户类型显示/隐藏字段 if (fieldName === 'customerType') { if (value === 'business') { form.showField('businessName'); form.hideField('personalId'); } else if (value === 'individual') { form.hideField('businessName'); form.showField('personalId'); } else { form.hideField('businessName'); form.hideField('personalId'); } } }); ```