### Real-Time Validation Example
Source: https://docs.knack.com/reference/record-and-form-events
Complete example showing how to prevent duplicate product selection using field change events and view-level methods.
```APIDOC
## Example: Real-Time Validation
### Description
Prevents duplicate product selection in a form. When a user selects a product from a dropdown (field_110), the script checks an existing DataTable view (view_216) on the same page. If the product already exists, a warning message is shown and the submit button is disabled. If the product is new, the message is cleared and submission is re-enabled.
### Code
```javascript
Knack.ready().then(async () => {
Knack.on('form:field-change:view_215', async ({ viewKey, fieldKey, value, formData }) => {
if (fieldKey === 'field_110') { // Product dropdown
// Retrieve current records from the table view on the same page
const tableData = await Knack.view('view_216').getData();
// Check if the selected product already exists
const productExists = tableData.records.some(record =>
record.field_110 === value
);
if (productExists) {
// Show a warning near the field
await Knack.view(viewKey).showFieldMessage('field_110', {
type: 'warning',
message: 'Product Already Added'
});
// Prevent form submission
await Knack.view(viewKey).setSubmitEnabled(false);
} else {
// Clear the warning and allow submission
await Knack.view(viewKey).clearFieldMessage('field_110');
await Knack.view(viewKey).setSubmitEnabled(true);
}
}
});
});
```
```
--------------------------------
### Event Data Structure Example
Source: https://docs.knack.com/reference/event-system-overview
Demonstrates the structure of the payload provided to an event listener, using the 'view:render' event as an example. The payload includes a 'viewKey' property.
```JavaScript
Knack.on('view:render', ({ viewKey }) => {
console.log('View rendered:', {
viewKey, // e.g., 'view_456'
});
});
```
--------------------------------
### Troubleshooting: Method Returns Undefined
Source: https://docs.knack.com/reference/constructing-view-urls-in-next-gen-apps
Example showing correct usage inside Knack.ready() to avoid undefined return from Knack.getBaseUrl().
```APIDOC
## Troubleshooting: Method Returns Undefined
### Description
Ensure Knack.getBaseUrl() is called inside Knack.ready() to avoid undefined return.
### Method
JavaScript function call
### Endpoint
Knack.getBaseUrl()
### Parameters
None
### Example
```javascript
// Correct
Knack.ready().then(async () => {
const baseUrl = Knack.getBaseUrl();
});
// Wrong
const baseUrl = Knack.getBaseUrl(); // May be undefined
```
```
--------------------------------
### Basic Filter Example
Source: https://docs.knack.com/reference/constructing-filters
Demonstrates how to construct a filter with match 'or' and rules for a field value or blank.
```APIDOC
## GET /v1/objects/{object_key}/records
### Description
Retrieve records from a Knack object with filters applied.
### Method
GET
### Endpoint
https://api.knack.com/v1/objects/{object_key}/records
### Parameters
#### Query Parameters
- **filters** (string) - Required - URL-encoded JSON object with keys 'match' and 'rules'.
### Request Example
```javascript
var api_url = 'https://api.knack.com/v1/objects/object_1/records';
var filters = {
'match': 'or',
'rules': [
{
'field':'field_1',
'operator':'is',
'value':'Dodgit'
},
{
'field':'field_1',
'operator':'is blank'
}
]
};
api_url += '?filters=' + encodeURIComponent(JSON.stringify(filters));
```
### Response
No response details provided in the source.
```
--------------------------------
### Example Response (200 OK)
Source: https://docs.knack.com/reference/object-based-put
The JSON response returned after a successful update, containing the updated record details.
```json
{
"id": "58643557d1ea9432222f3cbb",
"field_1": "Updated name",
"field_1_raw": "Updated name",
"field_16": "4913 Gnatty Creek Road
Westbury, NY 11590",
"field_16_raw": {
"street": "4913 Gnatty Creek Road",
"city": "Westbury",
"state": "NY",
"zip": "11590",
"latitude": 40.89964,
"longitude": -73.601586
},
"field_17": "http://www.pearlinc.com",
"field_17_raw": {
"url": "http://www.pearlinc.com"
},
"field_18": "Other",
"field_18_raw": "Other",
"field_31": "516-334-3077",
"field_31_raw": "516-334-3077"
}
```
--------------------------------
### Efficient CSS Selectors
Source: https://docs.knack.com/reference/best-practices
Examples comparing efficient, specific selectors against overly complex and slow selector chains.
```CSS
/* ✅ Efficient - specific but not overly complex */
.kn-page .kn-action-button {
background-color: #007bff;
}
/* ❌ Inefficient - overly specific and slow */
.kn-app > .kn-page-container > .kn-page > .kn-view > .kn-action-button {
background-color: #007bff;
}
/* ✅ Good for specific targeting */
#scene_123 #view_456.kn-form-view .kn-action-button {
background-color: #28a745;
}
```
--------------------------------
### Date Range Filter Example
Source: https://docs.knack.com/reference/constructing-filters
Demonstrates how to construct a filter for date/time fields with range and type parameters.
```APIDOC
## GET /v1/objects/{object_key}/records
### Description
Retrieve records from a Knack object with a date range filter applied.
### Method
GET
### Endpoint
https://api.knack.com/v1/objects/{object_key}/records
### Parameters
#### Query Parameters
- **filters** (string) - Required - URL-encoded JSON array of filter objects. For date range filters, include 'range' and 'type' keys.
### Request Example
```javascript
var api_url = 'https://api.knack.com/v1/objects/object_1/records';
var filters = [
{
"field":"field_3",
"operator":"is during the previous",
"range":3,
"type":"months"
}
];
api_url += '?filters=' + encodeURIComponent(JSON.stringify(filters));
```
### Response
No response details provided in the source.
```
--------------------------------
### Conditional Example: Dynamic Pricing
Source: https://docs.knack.com/docs/equations-overview
Implements complex pricing logic based on whether payment is early, late, or on time.
```text
{Time of Payment} > {Due Date} ? ({Cost} * 1.03) : ({Time of Payment} < {Due Date} ? {Cost} * 0.99 : {Cost})
```
--------------------------------
### Load jQuery with Knack.loadScript
Source: https://docs.knack.com/reference/external-resource-loading
Example of loading jQuery dynamically and using a fallback mechanism if the library fails to load.
```javascript
Knack.ready().then(async () => {
try {
await Knack.loadScript('https://code.jquery.com/jquery-3.6.0.min.js');
console.log('jQuery loaded! Version:', $.fn.jquery);
$(function () {
$('#my-button').click(function () {
alert('Button clicked!');
});
$('.fade-in').fadeIn(500);
});
} catch (error) {
console.error('Failed to load jQuery:', error);
document.getElementById('my-button').addEventListener('click', function () {
alert('Button clicked (fallback)!');
});
}
});
```
--------------------------------
### Ensuring Color Contrast
Source: https://docs.knack.com/reference/best-practices
Example of setting background and text colors to meet WCAG AA contrast requirements.
```CSS
.kn-page .kn-action-button {
background-color: #007bff; /* Meets WCAG AA contrast requirements with white text */
color: white;
}
```
--------------------------------
### View-Based GET Response
Source: https://docs.knack.com/reference/retrieving-one-record
Example JSON response for a view-based record retrieval.
```json
{
"id": "58643557d1ea9432222f3cb5",
"field_1": "BASCO",
"field_1_raw": "BASCO",
"field_16": "4295 Drainer Avenue Tallahassee, FL 32304",
"field_16_raw": {
"longitude": -84.177903,
"latitude": 30.463511,
"zip": "32304",
"state": "FL",
"city": "Tallahassee",
"street2": "",
"street": "4295 Drainer Avenue"
},
"field_18": "Entertainment",
"field_18_raw": "Entertainment",
"field_17": "http://www.basco.com",
"field_17_raw": {
"url": "http://www.basco.com"
},
"field_31": "850-644-1128",
"field_31_raw": "850-644-1128"
}
```
--------------------------------
### Customer Onboarding Workflow Example
Source: https://docs.knack.com/reference/record-and-form-events
Shows how to trigger specific business logic, such as onboarding workflows, when an enterprise customer record is created in a specific view.
```javascript
// Example: Customer onboarding workflow
Knack.on('record:create', ({ record, viewKey }) => {
if (viewKey === 'view_customer_form' && record.field_customer_type === 'Enterprise') {
console.log('New enterprise customer created:', record.field_company_name);
triggerEnterpriseOnboarding(record);
assignEnterpriseAccountManager(record);
sendEnterpriseWelcomeEmail(record.field_email);
}
});
```
--------------------------------
### Object-Based GET Response
Source: https://docs.knack.com/reference/retrieving-one-record
Example JSON response for an object-based record retrieval.
```json
{
"id": "58643557d1ea9432222f3cbb",
"field_1": "Pearl Architectural Design",
"field_1_raw": "Pearl Architectural Design",
"field_16": "4913 Gnatty Creek Road
Westbury, NY 11590",
"field_16_raw": {
"street": "4913 Gnatty Creek Road",
"city": "Westbury",
"state": "NY",
"zip": "11590",
"latitude": 40.89964,
"longitude": -73.601586
},
"field_17": "http://www.pearlinc.com",
"field_17_raw": {
"url": "http://www.pearlinc.com"
},
"field_18": "Services",
"field_18_raw": "Services",
"field_31": "516-334-3077",
"field_31_raw": "516-334-3077"
}
```
--------------------------------
### Retrieve User Data at Startup
Source: https://docs.knack.com/reference/schema-access-methods
Use this approach to fetch user data once during the initial application load.
```javascript
Knack.ready().then(() => {
Knack.getUser().then(user => {
// Runs only once when app loads
})
})
```
--------------------------------
### getDateMonthOfYearName(DATE)
Source: https://docs.knack.com/docs/text-formula-functions
Gets the month of the year from a date field. For example, getDateMonthOfYearName({Date}) returns 'April'.
```APIDOC
## getDateMonthOfYearName(DATE)
### Description
Gets the month of the year from a date field.
### Function Signature
`getDateMonthOfYearName(DATE)`
### Parameters
- **DATE** (date field) - Required - The date field from which to extract the month of the year.
### Example
`getDateMonthOfYearName({Date}) = April`
```
--------------------------------
### Access Next-Gen User Information
Source: https://docs.knack.com/docs/user-tokens
Use Knack.ready() to ensure the app is initialized before retrieving user details or checking profile keys.
```JavaScript
Knack.ready().then(async () => {
// Get current user information
const user = await Knack.getUser();
if (user) {
console.log('Current user:', user);
console.log('User email:', user.email);
console.log('User name:', user.name);
} else {
console.log('No user is currently logged in');
}
// Check if the current user has a specific profile/role key
try {
const hasProfile = await Knack.hasProfileKey?.('profile_1'); // e.g., 'profile_1'
if (typeof hasProfile === 'boolean') {
console.log('Has profile_1?', hasProfile);
}
} catch (e) {
// Swallow if not supported
}
});
```
--------------------------------
### Knack.ready()
Source: https://docs.knack.com/reference/schema-access-methods
Initializes the Knack object and ensures the React application has finished mounting before executing custom code.
```APIDOC
## Knack.ready()
### Description
Initializes the Knack object and ensures the React application has finished mounting before executing custom code.
### Method
ready()
### Endpoint
Knack.ready()
### Parameters
None
### Request Example
```javascript
Knack.ready().then(async () => {
// All your custom code goes here
console.log('Knack is ready for customization!');
});
```
### Response
#### Success Response
- **Promise** - Resolves when the Knack object is fully initialized.
#### Response Example
```javascript
// No explicit response value; the promise resolves when ready.
```
```
--------------------------------
### getDateDayOfWeekName(DATE)
Source: https://docs.knack.com/docs/text-formula-functions
Gets the day of the week from a date field. For example, getDateDayOfWeekName({Date}) returns 'Friday'.
```APIDOC
## getDateDayOfWeekName(DATE)
### Description
Gets the day of the week from a date field.
### Function Signature
`getDateDayOfWeekName(DATE)`
### Parameters
- **DATE** (date field) - Required - The date field from which to extract the day of the week.
### Example
`getDateDayOfWeekName({Date}) = Friday`
```
--------------------------------
### Conditional Example: Date Difference Calculations
Source: https://docs.knack.com/docs/equations-overview
Calculates date differences while handling blank start or end dates.
```text
{End Date} > 0 & {Start Date} > 0 ? {End Date} - {Start Date} : {Start Date} > 0 ? currentTime() - {Start Date} : 0
```
--------------------------------
### Desktop & Mobile Design Example
Source: https://docs.knack.com/reference/using-css-with-next-gen-knack
Uses media queries to toggle visibility and styling of navigation elements between desktop and mobile views.
```css
/* Desktop styles */
.kn-main-nav-container {
display: flex;
justify-content: space-between;
align-items: center;
}
.kn-main-nav-toggle {
display: none;
}
/* Mobile styles */
@media (max-width: 768px) {
.kn-main-nav-container {
display: none;
}
.kn-header-mobile .kn-main-nav-toggle {
display: block;
background: transparent;
border: 2px solid #007bff;
color: #007bff;
padding: 0.5rem;
border-radius: 4px;
}
.kn-header-mobile .kn-main-nav-toggle:hover {
background-color: #007bff;
color: white;
}
}
```
--------------------------------
### Sample prompt for building a Knack app
Source: https://docs.knack.com/docs/mcp
A prompt to use after connecting the Knack MCP server. It asks the AI to create a data model with Projects, Tasks, and People tables, including fields and relationships, and to provide a summary.
```text
I need to build a project management application in Knack.
The app needs:
- A Projects table with fields for: project name, status (active/on hold/completed),
start date, due date, and a description
- A Tasks table with fields for: task name, assignee (text), priority
(high/medium/low), due date, completion checkbox, and notes
- A connection from Tasks to Projects so each task belongs to a project
- A People table for team members with: full name, email, role, and department
Please create this data model in my Knack application, using descriptive names
for all tables and fields. After creating the schema, give me a summary of
what was built.
```
--------------------------------
### Multiple Records Response
Source: https://docs.knack.com/docs/response-format
Example JSON response for a GET request returning multiple records, including pagination metadata.
```json
{
"total_pages": 1,
"current_page": 1,
"total_records": 2,
"records": [
{
"id": "58643557d1ea9432222f3cbb",
"field_1": "Pearl Architectural Design",
"field_1_raw": "Pearl Architectural Design",
"field_17": "http://www.pearlinc.com",
"field_17_raw": {
"url": "http://www.pearlinc.com"
},
"field_18": "Services",
"field_18_raw": "Services",
"field_31": "516-334-3077",
"field_31_raw": "516-334-3077"
},
{
"id": "58643556d1ea9432222f3ca6",
"field_1": "Kelly and Cohen",
"field_1_raw": "Kelly and Cohen",
"field_17": "http://www.kellycohen.com",
"field_17_raw": {
"url": "http://www.kellycohen.com"
},
"field_18": "Services",
"field_18_raw": "Services",
"field_31": "315-296-4146",
"field_31_raw": "315-296-4146"
}
]
}
```
--------------------------------
### Single Record Response
Source: https://docs.knack.com/docs/response-format
Example JSON response for a successful GET, POST, or PUT request returning a single record.
```json
{
"id": "58643557d1ea9432222f3cbb",
"field_1": "Pearl Architectural Design",
"field_1_raw": "Pearl Architectural Design",
"field_17": "http://www.pearlinc.com",
"field_17_raw": {
"url": "http://www.pearlinc.com"
},
"field_18": "Services",
"field_18_raw": "Services",
"field_31": "516-334-3077",
"field_31_raw": "516-334-3077"
}
```
--------------------------------
### Identify Next-Gen App HTML Patterns
Source: https://docs.knack.com/reference/using-developer-tools-to-inspect-css-classes-and-ids
Examples of HTML structure using standard Knack naming conventions for navigation and page content.
```html
Page Title
```
--------------------------------
### JSON Response for Multiple Records
Source: https://docs.knack.com/docs/retrieving-multiple-records
An abbreviated example of the JSON response returned by the GET request, showing record fields and raw data.
```json
{
"total_pages": 1,
"current_page": 1,
"total_records": 15,
"records": [
{
"id": "58643557d1ea9432222f3cb5",
"field_1": "BASCO",
"field_1_raw": "BASCO",
"field_16": "4295 Drainer Avenue Tallahassee, FL 32304",
"field_16_raw": {
"longitude": -84.177903,
"latitude": 30.463511,
"zip": "32304",
"state": "FL",
"city": "Tallahassee",
"street2": "",
"street": "4295 Drainer Avenue"
},
"field_17": "http://www.basco.com",
"field_17_raw": {
"url": "http://www.basco.com"
},
"field_18": "Entertainment",
"field_18_raw": "Entertainment",
"field_14_raw": [
{
"first": "Barbara",
"last": "Waters"
},
{
"first": "Josefa",
"last": "Willems"
}
],
"field_14": "Barbara Waters Josefa Willems"
},
{
"id": "58643557d1ea9432222f3cb1",
"field_1": "Cavages",
"field_1_raw": "Cavages",
"field_16": "3885 Mount Street Saginaw, MI 48607",
"field_16_raw": {
"street": "3885 Mount Street",
"city": "Saginaw",
"state": "MI",
"zip": "48607",
"latitude": 44.352592,
"longitude": -84.419193
},
"field_17": "http://www.cavages.com",
"field_17_raw": {
"url": "http://www.cavages.com"
},
"field_18": "Health Care",
"field_18_raw": "Health Care",
"field_14_raw": [
{
"first": "Daniel",
"last": "Navarrete"
},
{
"first": "Mark",
"last": "Silverstein"
}
],
"field_14": "Daniel Navarrete Mark Silverstein"
},
..........
```
--------------------------------
### Setup Custom File Input
Source: https://docs.knack.com/docs/fileimage-uploads
Use this snippet inside the Knack.ready() block to attach the file upload handler to a specific DOM element.
```javascript
// Add this inside the Knack.ready() block:
setupFileUpload('#my-file-input', 'field_123', 'object_456');
```
--------------------------------
### Cycle through selected checkboxes in a table
Source: https://docs.knack.com/docs/javascript-jquery-examples
Iterates over all checked checkboxes in a specific table view. Inside the loop, you can add code to get the record id or row value. The example shows how to get the record id from the closest row's id attribute. Replace view_5 with your view key.
```JavaScript
// Cycle through selected checkboxes. Use this in any code that needs to get the checked IDs
$('#view_5 tbody input[type=checkbox]:checked').each(function() {
// add code here to get record id or row value
var id = $(this).closest('tr').attr('id'); // record id
});
```
--------------------------------
### Single Record Response
Source: https://docs.knack.com/docs/response-format
Example of a successful response for a GET, POST, or PUT request that returns a single record. The response body is a JSON object representing the record.
```APIDOC
## Single Record Response
### Description
Example of a successful response for a GET, POST, or PUT request that returns a single record. The response body is a JSON object representing the record.
### Response
#### Success Response (200 OK)
- **id** (string) - The unique record ID.
- **field_1** (string) - The value of field_1.
- **field_1_raw** (string) - The raw value of field_1.
- **field_17** (string) - The value of field_17, possibly containing HTML.
- **field_17_raw** (object) - The raw value of field_17, containing a URL.
- **field_18** (string) - The value of field_18.
- **field_18_raw** (string) - The raw value of field_18.
- **field_31** (string) - The value of field_31.
- **field_31_raw** (string) - The raw value of field_31.
#### Response Example
```json
{
"id": "58643557d1ea9432222f3cbb",
"field_1": "Pearl Architectural Design",
"field_1_raw": "Pearl Architectural Design",
"field_17": "http://www.pearlinc.com",
"field_17_raw": {
"url": "http://www.pearlinc.com"
},
"field_18": "Services",
"field_18_raw": "Services",
"field_31": "516-334-3077",
"field_31_raw": "516-334-3077"
}
```
```
--------------------------------
### Listen for Record Events
Source: https://docs.knack.com/reference/record-and-form-events
Demonstrates how to use Knack.on to listen for record creation, updates, and deletions within the Knack.ready lifecycle hook.
```javascript
Knack.ready().then(async () => {
// Listen for record creation
Knack.on('record:create', ({ record, viewKey }) => {
console.log('Record created:', record);
console.log('In view:', viewKey);
if (record.field_priority === 'High') {
console.log('High priority record created, sending notifications');
sendNotificationToManagers(record);
}
});
// Listen for record updates
Knack.on('record:update', ({ record, viewKey }) => {
console.log('Record updated:', record);
processRecordUpdate(record, viewKey);
});
// Listen for record deletion
Knack.on('record:delete', ({ record, viewKey }) => {
console.log('Record deleted:', record);
});
});
```
--------------------------------
### Initialize Knack Customization
Source: https://docs.knack.com/reference/schema-access-methods
The mandatory entry point for all JavaScript customizations. Ensures the Knack object is initialized and the application is mounted.
```javascript
Knack.ready().then(async () => {
// All your custom code goes here
console.log('Knack is ready for customization!');
});
```
--------------------------------
### Multiple Records Response
Source: https://docs.knack.com/docs/response-format
Example of a successful response for a GET request that returns multiple records. The response body is a JSON object containing pagination metadata and an array of records.
```APIDOC
## Multiple Records Response
### Description
Example of a successful response for a GET request that returns multiple records. The response body is a JSON object containing pagination metadata and an array of records.
### Response
#### Success Response (200 OK)
- **total_pages** (integer) - Total number of pages of results which match your filters (if any).
- **current_page** (integer) - The current page of the records returned by your request.
- **total_records** (integer) - The total number of records which match your filters (if any).
- **records** (array) - An array of JSON objects, where each object represents a record.
#### Response Example
```json
{
"total_pages": 1,
"current_page": 1,
"total_records": 2,
"records": [
{
"id": "58643557d1ea9432222f3cbb",
"field_1": "Pearl Architectural Design",
"field_1_raw": "Pearl Architectural Design",
"field_17": "http://www.pearlinc.com",
"field_17_raw": {
"url": "http://www.pearlinc.com"
},
"field_18": "Services",
"field_18_raw": "Services",
"field_31": "516-334-3077",
"field_31_raw": "516-334-3077"
},
{
"id": "58643556d1ea9432222f3ca6",
"field_1": "Kelly and Cohen",
"field_1_raw": "Kelly and Cohen",
"field_17": "http://www.kellycohen.com",
"field_17_raw": {
"url": "http://www.kellycohen.com"
},
"field_18": "Services",
"field_18_raw": "Services",
"field_31": "315-296-4146",
"field_31_raw": "315-296-4146"
}
]
}
```
```
--------------------------------
### Listen for View Render Events
Source: https://docs.knack.com/reference/page-and-view-events-1
Demonstrates how to listen for general view renders, specific view keys, and specific view types using Knack.on within the Knack.ready lifecycle hook.
```javascript
Knack.ready().then(async () => {
// Listen for any view render
Knack.on('view:render', ({ viewKey }) => {
console.log('View rendered:', viewKey);
// Use for analytics, logging, or business logic
});
// Listen for a specific view render
Knack.on('view:render:view_456', ({ viewKey }) => {
console.log('Contact form rendered');
// Trigger view-specific business logic
});
// Listen for specific view types
Knack.on('view:render:form', ({ viewKey }) => {
console.log('A form view was rendered:', viewKey);
// Handle form-specific logic
});
});
```
--------------------------------
### getLinkLabel(LINK)
Source: https://docs.knack.com/docs/text-formula-functions
Extracts the label from a link field. For example, getLinkLabel({Link}) returns 'Example!'.
```APIDOC
## getLinkLabel(LINK)
### Description
Extracts the label from a link field.
### Function Signature
`getLinkLabel(LINK)`
### Parameters
- **LINK** (link field) - Required - The link field from which to extract the label.
### Example
`getLinkLabel({Link}) = Example!`
```
--------------------------------
### Apply Custom CSS Styles
Source: https://docs.knack.com/reference/using-css-with-next-gen-knack
Example CSS demonstrating how to override default Knack styles using higher specificity selectors for navigation, buttons, and specific scenes.
```css
/* Change the main navigation background */
.kn-page .kn-main-nav {
background-color: #007bff;
}
/* Style all action buttons */
.kn-page .kn-action-button {
background-color: #28a745;
border-radius: 6px;
padding: 0.75rem 1.5rem;
}
/* Customize a specific page */
#scene_123 {
background-color: #f8f9fa;
max-width: 1200px;
margin: 0 auto;
}
```
--------------------------------
### CSS Testing Example
Source: https://docs.knack.com/reference/using-developer-tools-to-inspect-css-classes-and-ids
An example of CSS rules applied to a form view during the testing process in developer tools.
```css
.kn-page .kn-form-view {
/* styles - using higher specificity */
background-color: #f8f9fa;
border-radius: 8px;
padding: 20px;
}
```
--------------------------------
### Basic Usage of Knack.getBaseUrl()
Source: https://docs.knack.com/reference/constructing-view-urls-in-next-gen-apps
Wrap your code in Knack.ready() to ensure the application is fully loaded before accessing the base URL.
```JavaScript
Knack.ready().then(async () => {
const baseUrl = Knack.getBaseUrl();
console.log('App base URL is: ', baseUrl);
});
```
--------------------------------
### Change Calendar Start Date
Source: https://docs.knack.com/docs/javascript-jquery-examples
Updates the calendar view start date by appending a date parameter to the current URL when the scene renders.
```javascript
/* Change the scene_1 to the scene key of your choice, or replace with any to work on all pages. */
$(document).on('knack-scene-render.scene_#', function(event, scene, data) {
var url = window.location.href;
url += "?view_#_date='2018-05-01'"
window.location.href = url;
});
```
--------------------------------
### Knack.ready() and Knack.hasProfileKey()
Source: https://docs.knack.com/reference/user-tokens
Next-Gen Knack methods to wait for app readiness and check if the current user has a specific profile/role key.
```APIDOC
## Knack.ready()
### Description
Returns a promise that resolves when the Knack app is ready.
### Method
Knack.ready()
### Returns
- **Promise** - Resolves when the app is ready.
## Knack.hasProfileKey(profileKey)
### Description
Checks if the current user has a specific profile/role key. Returns a boolean.
### Parameters
- **profileKey** (string) - The profile key to check, e.g., 'profile_1'.
### Returns
- **boolean** - True if the user has the profile, false otherwise.
### Example
```javascript
Knack.ready().then(async () => {
// Get current user information
const user = await Knack.getUser();
if (user) {
console.log('Current user:', user);
console.log('User email:', user.email);
console.log('User name:', user.name);
} else {
console.log('No user is currently logged in');
}
// Check if the current user has a specific profile/role key
try {
const hasProfile = await Knack.hasProfileKey?.('profile_1'); // e.g., 'profile_1'
if (typeof hasProfile === 'boolean') {
console.log('Has profile_1?', hasProfile);
}
} catch (e) {
// Swallow if not supported
}
});
```
```
--------------------------------
### Knack.getApplicationDetails()
Source: https://docs.knack.com/reference/schema-access-methods
Retrieves metadata about the application.
```APIDOC
## Knack.getApplicationDetails()
### Description
Retrieves metadata about the application.
### Method
getApplicationDetails()
### Endpoint
Knack.getApplicationDetails()
### Parameters
None
### Request Example
```javascript
const appDetails = await Knack.getApplicationDetails();
console.log('Application details:', appDetails);
```
### Response
#### Success Response
- **appDetails** (SchemaApplicationDetails) - Application metadata.
- **id** (string) - Application ID.
- **name** (string) - Application name.
- **slug** (string) - Application slug.
- **description** (string) - Application description.
- **settings** (object) - Application settings.
- **users** (object) - User settings.
- **registration_type** (string) - Registration type.
- **invitation_required** (boolean) - Whether invitation is required.
- **self_registration** (boolean) - Whether self-registration is allowed.
- **region** (string) - Region.
- **timezone** (string) - Timezone.
- **language** (string) - Language.
#### Response Example
```javascript
// Example response (structure not specified in source)
```
```
--------------------------------
### Different Start/End Dates with Times Formulas
Source: https://docs.knack.com/docs/importing-special-data-types
Formulas to combine Start Date, End Date, Start Time, and End Time columns into the required import format.
```google-sheets
=TEXT(A1, "dd/mm/yyyy") & " " & TEXT(C1, "h:mmam/pm") & " to " & TEXT(B1, "dd/mm/yyyy") & " " & TEXT(D1, "h:mmam/pm")
```
```excel
=CONCATENATE(TEXT(A1,"dd/mm/yyyy")," ",TEXT(C1,"h:mm AM/PM")," to ",TEXT(B1,"dd/mm/yyyy")," ",TEXT(D1,"h:mm AM/PM"))
```
--------------------------------
### Initialize form interaction
Source: https://docs.knack.com/reference/event-system-overview
Sets up the form API listener after the application is ready.
```JavaScript
Knack.ready().then(() => {
Knack.on('view:render', ({ viewKey }) => {
const form = Knack.page.getForm(viewKey);
if (form) {
// Your setValue and focus calls here
} else {
console.log('Form not found for view:', viewKey);
}
});
});
```
--------------------------------
### Initialize Knack Object API with Knack.ready()
Source: https://docs.knack.com/reference/the-next-gen-knack-object-api
All API interactions must be wrapped in the Knack.ready() promise to ensure the application environment is fully initialized before execution.
```javascript
Knack.ready().then(async () => {
// Your code here
const user = await Knack.getUser();
console.log('Current user:', user);
});
```
--------------------------------
### Change the 'add filter' text
Source: https://docs.knack.com/docs/javascript-jquery-examples
This example will change the 'add filter' text for any view.
```javascript
$(document).on('knack-view-render.any', function(event, view, record) {
$('.kn-add-filter').text('Advanced Search')
});
```
--------------------------------
### currentTime
Source: https://docs.knack.com/docs/date-equation-functions
Inserts the current time as a date or number value. Example: currentTime() = 07/08/2024.
```APIDOC
## currentTime
### Description
Inserts the current time as a date or number value.
### Function
currentTime()
### Example
currentTime() = 07/08/2024
### Notes
- Equation type must be set to "Date" to use this function.
```
--------------------------------
### Basic Event Syntax with Knack.on()
Source: https://docs.knack.com/reference/event-system-overview
Shows the basic pattern for listening to events using Knack.on(). The first listener catches any event of a given type, while the second listens for a specific event by appending an ID to the event type.
```JavaScript
Knack.ready().then(async () => {
// Listen for any event of this type
Knack.on('event:type', (payload) => {
console.log('Event triggered:', payload);
});
// Listen for a specific event
Knack.on('event:type:specific_id', (payload) => {
console.log('Specific event triggered:', payload);
});
});
```
--------------------------------
### Object-Based GET Request
Source: https://docs.knack.com/reference/retrieving-one-record
Retrieves a specific record using the object-based API endpoint.
```bash
curl -X GET "https://api.knack.com/v1/objects/object_1/records/58643557d1ea9432222f3cbb" \
-H "X-Knack-Application-Id: YOUR-APP-ID" \
-H "X-Knack-REST-API-Key: YOUR-API-KEY"
```
--------------------------------
### Combine with Record IDs
Source: https://docs.knack.com/reference/constructing-view-urls-in-next-gen-apps
Example of using Knack.getBaseUrl() with Knack.getCurrentRecordId() to create URLs for specific records.
```APIDOC
## Combine with Record IDs
### Description
Use Knack.getBaseUrl() alongside Knack.getCurrentRecordId() to create URLs for specific records, such as an edit view.
### Method
JavaScript function calls
### Endpoint
Knack.getBaseUrl() and Knack.getCurrentRecordId()
### Parameters
None
### Example
```javascript
Knack.ready().then(async () => {
Knack.on('page:render', ({ page }) => {
const baseUrl = Knack.getBaseUrl();
const recordId = Knack.getCurrentRecordId(); // Get current record
// Build a URL to an edit view for this record
const editUrl = `${baseUrl}/view_999?record=${recordId}`;
console.log('Edit URL: ', editUrl);
});
});
```
```
--------------------------------
### CSS Style Prioritization Methods
Source: https://docs.knack.com/reference/prioritize-your-styles
Examples demonstrating how to use increased selector specificity and the !important attribute to override default styles.
```css
/* Specificity */
.kn-content #kn-app-menu ul {
background: #DDD;
}
/* !important */
#kn-app-menu ul {
background: #DDD !important;
}
```
--------------------------------
### getNameTitle(NAME)
Source: https://docs.knack.com/docs/text-formula-functions
Extracts the title from a person field. For example, getNameTitle({Name}) returns 'Dr.'.
```APIDOC
## getNameTitle(NAME)
### Description
Extracts the title from a person field.
### Function Signature
`getNameTitle(NAME)`
### Parameters
- **NAME** (person field) - Required - The person field from which to extract the title.
### Example
`getNameTitle({Name}) = Dr.`
```
--------------------------------
### getAddressState(ADDRESS)
Source: https://docs.knack.com/docs/text-formula-functions
Extracts the state from an address field. Example: getAddressState({Address}) returns VA.
```APIDOC
## getAddressState(ADDRESS)
### Description
Extracts the state from an address field.
### Function Signature
getAddressState(ADDRESS)
### Parameters
- **ADDRESS** (address) - Required - The address field to extract from.
### Example
getAddressState({Address}) = VA
```
--------------------------------
### Next-Gen Data Handling and CSS Alert Styling
Source: https://docs.knack.com/reference/custom-javascript-differences-in-classic-and-next-gen-apps
Demonstrates using the Knack.ready() event-driven pattern for data analysis and associated CSS for dynamic UI alerts.
```JavaScript
Knack.ready().then(async () => {
Knack.on('records:render:view_789', ({ records, viewKey }) => {
console.log('Table data loaded:', records.length, 'records');
// Analyze data for business insights
const statusCounts = records.reduce((acc, record) => {
const status = record.field_status;
acc[status] = (acc[status] || 0) + 1;
return acc;
}, {});
console.log('Status distribution:', statusCounts);
// Business logic based on data
if (statusCounts.Inactive > statusCounts.Active) {
console.warn('More inactive than active records');
triggerStatusAlert(statusCounts);
} else {
// Remove alert if condition no longer met
document.body.classList.remove('status-alert-active');
}
});
function triggerStatusAlert(statusCounts) {
// Add CSS class to trigger visual alert
document.body.classList.add('status-alert-active');
// Log for debugging/analytics
console.warn('Status Alert Triggered:', statusCounts);
console.table(statusCounts);
// Could also send to external services
// sendToAnalytics('status_alert', statusCounts);
}
});
/* Status alert banner - hidden by default */
.status-alert-banner {
display: none;
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
border-radius: 4px;
padding: 1rem;
margin: 1rem 0;
font-weight: 500;
position: relative;
}
.status-alert-banner::before {
content: '⚠️ ';
font-size: 1.2em;
margin-right: 0.5rem;
}
/* Show alert when status-alert-active class is added to body */
.status-alert-active .status-alert-banner {
display: block;
animation: slideIn 0.3s ease-out;
}
/* Optional: Style the table view when alert is active */
.status-alert-active .scene_789_view_789 {
border-left: 4px solid #dc3545;
}
.status-alert-active .scene_789_view_789 .kn-table-view {
background-color: #fff5f5;
}
/* Animation for alert appearance */
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Close button styling (optional) */
.status-alert-banner .close-btn {
position: absolute;
top: 0.5rem;
right: 0.5rem;
background: none;
border: none;
color: #721c24;
font-size: 1.2em;
cursor: pointer;
padding: 0.25rem;
border-radius: 2px;
}
.status-alert-banner .close-btn:hover {
background-color: rgba(0,0,0,0.1);
}
```
--------------------------------
### Set and focus media fields
Source: https://docs.knack.com/reference/event-system-overview
Demonstrates setting an image URL and focusing the field.
```JavaScript
form.setValue('field_63', "https://example.com/image.jpg");
form.focus('field_63');
```
--------------------------------
### getAddressCity(ADDRESS)
Source: https://docs.knack.com/docs/text-formula-functions
Extracts the city from an address field. Example: getAddressCity({Address}) returns Amonate.
```APIDOC
## getAddressCity(ADDRESS)
### Description
Extracts the city from an address field.
### Function Signature
getAddressCity(ADDRESS)
### Parameters
- **ADDRESS** (address) - Required - The address field to extract from.
### Example
getAddressCity({Address}) = Amonate
```
--------------------------------
### currentDate
Source: https://docs.knack.com/docs/date-equation-functions
Inserts the current date (midnight) as a date or number value. Example: currentDate() = 07/08/2024.
```APIDOC
## currentDate
### Description
Inserts the current date (midnight) as a date or number value.
### Function
currentDate()
### Example
currentDate() = 07/08/2024
### Notes
- Equation type must be set to "Date" to use this function.
```