2602 Using Pipes In Components
Using Pipes in Components
Overview
In the previous article, you learned what pipes are and how they work architecturally. Now it's time to put that knowledge into practice by implementing pipes in Tadabase components. This article covers practical, hands-on techniques for using pipes to create dynamic, data-driven forms and applications.
Where Pipes Can Be Used
Pipes can be integrated into various Tadabase components:
Form Components
- Text fields: Auto-populate, format, or validate text input
- Dropdowns: Load options dynamically from external sources
- Number fields: Calculate values, format numbers, perform conversions
- Date fields: Set dynamic dates, format display, calculate date ranges
- Hidden fields: Store pipe results without displaying to user
- Display fields: Show pipe results as read-only information
Data Components
- Details pages: Display enriched data from external sources
- Data tables: Format displayed values using pipes
- Rich text: Embed dynamic content from APIs
Action Contexts
- Form submission: Process data before saving
- Record rules: Trigger pipes when records change
- Action links: Execute pipes when user clicks buttons
Loading External Data
One of the most common uses for pipes is loading data from external APIs into your forms.
Example 1: Address Lookup
Scenario: User enters a zip code, and the city and state automatically populate. Setup Steps:- Create the pipe:
- Navigate to Builder → Pipes
- Click Add New Pipe
- Name: "Zip Code Lookup"
- URL:
https://api.zippopotam.us/us/{zip_code} - Method: GET
- No authentication required (public API)
- Configure response mapping:
- City path:
places[0].place name - State path:
places[0].state - State abbreviation path:
places[0].state abbreviation
- City path:
- Add to form:
- Create fields: Zip Code (text), City (text), State (text)
- Open Zip Code field settings
- Add Field Change action
- Select "Run Pipe"
- Choose "Zip Code Lookup" pipe
- Map
{zip_code}to Zip Code field - Map City result to City field
- Map State result to State field
- Test the form:
- Enter a valid US zip code (e.g., "10001")
- Watch City and State auto-populate
- Try invalid zip code to see error handling
{
"post code": "10001",
"country": "United States",
"country abbreviation": "US",
"places": [
{
"place name": "New York",
"longitude": "-73.9967",
"state": "New York",
"state abbreviation": "NY",
"latitude": "40.7484"
}
]
}
Example 2: Product Information Lookup
Scenario: User enters product SKU, and details are fetched from inventory API. Pipe Configuration:- URL:
https://api.yourcompany.com/products/{sku} - Headers:
Authorization: Bearer YOUR_API_KEY - Method: GET
- Product Name:
product.name - Description:
product.description - Price:
product.price - Stock Level:
inventory.quantity - Supplier:
supplier.name
- SKU field with pipe trigger on change
- Product name field (auto-populated, read-only)
- Description field (rich text, auto-populated)
- Price field (number, auto-populated)
- Stock display (show availability status)
Example 3: Weather Data
Scenario: Display current weather for event location. Setup:- API: OpenWeatherMap
- URL:
https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key} - Trigger: On page load or when city field changes
- Temperature:
main.temp(convert Kelvin to Fahrenheit) - Conditions:
weather[0].description - Humidity:
main.humidity - Wind speed:
wind.speed
Dynamic Form Values
Pipes enable sophisticated form behaviors where field values depend on user input and external data.
Dependent Dropdowns
Scenario: Country selection determines available states/provinces. Implementation:- Country dropdown:
- Populate with static list or from table
- Add onChange trigger
- Create State pipe:
- Name: "Get States"
- URL:
https://api.locations.com/states?country={country_code} - Response: Array of states
- Map to:
states[]
- State dropdown:
- Source: Pipe results
- Trigger: When country changes
- Clear existing value when country changes
- City dropdown (third level):
- Source: Another pipe based on selected state
- URL:
https://api.locations.com/cities?state={state_code}
- Country change → Reset State and City
- Country change → Load States for selected country
- State change → Reset City
- State change → Load Cities for selected state
Calculated Fields
Scenario: Calculate shipping cost based on weight and destination. Setup:- Input fields:
- Weight (number)
- Destination zip code (text)
- Shipping method (dropdown: Standard, Express, Overnight)
- Shipping rate pipe:
- Name: "Calculate Shipping"
- URL:
https://api.shipper.com/rates - Method: POST
- Body:
{ "weight": {weight}, "destination": {zip_code}, "service": {shipping_method} } - Response:
rates[0].cost
- Cost field:
- Number field (read-only)
- Populated by pipe result
- Format as currency
- Updates automatically when inputs change
- Trigger conditions:
- Execute pipe when: All three inputs have values
- Show loading indicator during calculation
- Handle errors gracefully (API down, invalid zip code)
Conditional Field Visibility
Scenario: Show additional fields based on validation result. Example: International address handling- User enters country
- Pipe validates if country requires additional documentation
- If yes, show document upload fields
- If no, hide those fields
- Hidden field stores pipe result (true/false)
- Conditional rules show/hide fields based on hidden field value
- Pipe executes on country selection
Form Validation with Pipes
Pipes provide powerful real-time validation capabilities.
Email Validation
Scenario: Verify email address exists and is deliverable. Setup:- Create validation pipe:
- Name: "Validate Email"
- URL:
https://api.emailverification.com/verify?email={email} - Headers:
Authorization: Bearer YOUR_KEY - Response path:
result.deliverable(returns true/false)
- Form field setup:
- Email field (text with email validation)
- Hidden field: Validation result
- Display field: Validation message
- Validation logic:
- User enters email
- Pipe executes on blur (when user leaves field)
- Result stored in hidden field
- Display field shows: "Valid email" or "Email not deliverable"
- Form submission prevented if invalid
- User feedback:
- Green checkmark for valid email
- Red warning for invalid email
- Loading spinner during validation
Business Validation
Scenario: Validate business tax ID number. Pipe configuration:- URL:
https://api.irs.gov/verify?ein={tax_id} - Response includes: Valid, business name, status
- Tax ID field triggers validation on complete (9 digits)
- If valid: Auto-populate business name field
- If invalid: Show error, prevent form submission
- If suspended: Show warning, require confirmation
Credit Card Validation
Scenario: Verify credit card details before processing. Security note: Never send full credit card numbers to your own servers. Use payment processor APIs directly. Setup:- Use Stripe.js or similar client-side library
- Pipe validates card format and existence
- Returns token for secure processing
- Store token, not card number
Inventory Validation
Scenario: Check if sufficient inventory exists before order submission. Implementation:- User selects product and quantity
- Pipe queries inventory API:
- URL:
https://api.inventory.com/check?sku={sku}&qty={quantity} - Response:
{ "available": true, "stock": 150 }
- URL:
- Validation logic:
- If available: Allow order
- If not available: Show "Out of stock" message
- If low stock: Show "Only X remaining" warning
- Real-time updates:
- Re-check inventory periodically
- Warn if stock decreases during order process
Tadabase Functions
Tadabase provides built-in functions for common data manipulation tasks.
Text Functions
1. Upper case conversion- Function:
upper({text_field}) - Use case: Standardize names, codes
- Example: "john smith" → "JOHN SMITH"
- Function:
lower({text_field}) - Use case: Email addresses, usernames
- Example: "USER@EMAIL.COM" → "user@email.com"
- Function:
trim({text_field}) - Use case: Clean user input
- Example: " hello " → "hello"
- Function:
substring({text_field}, start, length) - Use case: Extract parts of strings
- Example:
substring("Order-12345", 6, 5)→ "12345"
- Function:
concat({first_name}, " ", {last_name}) - Use case: Combine multiple fields
- Example: "John" + " " + "Smith" → "John Smith"
- Function:
replace({text_field}, "find", "replace") - Use case: Standardize formats
- Example:
replace("555-1234", "-", ".")→ "555.1234"
// Clean and format user input
upper(trim({first_name})) + " " + upper(trim({last_name}))
// Result: Clean, properly formatted full name in uppercase
Date Functions
1. Current date and time- Function:
now() - Use case: Timestamp records
- Returns: Current date and time
- Function:
today() - Use case: Default date fields to today
- Returns: Current date (no time)
- Function:
dateAdd({date_field}, days) - Use case: Calculate due dates, expiration dates
- Example:
dateAdd(today(), 30)→ 30 days from now
- Function:
dateSubtract({date_field}, days) - Use case: Calculate start dates
- Example:
dateSubtract(today(), 7)→ 7 days ago
- Function:
dateDiff({date1}, {date2}) - Use case: Age calculations, duration
- Returns: Number of days between dates
- Function:
formatDate({date_field}, "format") - Use case: Display dates in specific format
- Formats: "MM/DD/YYYY", "YYYY-MM-DD", "DD-MMM-YYYY", etc.
- Functions:
year({date}),month({date}),day({date}) - Use case: Filtering, grouping by date parts
// Calculate project deadline (30 days from start date)
dateAdd({start_date}, 30)
// Calculate project duration in days
dateDiff({end_date}, {start_date})
// Display formatted date
formatDate({deadline}, "MMM DD, YYYY") // Result: "Jan 28, 2026"
Number Functions
1. Round numbers- Function:
round({number_field}, decimals) - Use case: Price calculations, percentages
- Example:
round(3.14159, 2)→ 3.14
- Function:
abs({number_field}) - Use case: Distance calculations, differences
- Example:
abs(-5)→ 5
- Function:
min({num1}, {num2}, ...) - Use case: Find lowest value
- Example:
min(10, 5, 8)→ 5
- Function:
max({num1}, {num2}, ...) - Use case: Find highest value
- Example:
max(10, 5, 8)→ 10
- Function:
sum({num1}, {num2}, ...) - Use case: Total calculations
- Example:
sum({price}, {tax}, {shipping})
- Function:
avg({num1}, {num2}, ...) - Use case: Calculate averages
- Functions:
ceil({number}),floor({number}) - Use case: Rounding up or down
- Examples:
ceil(3.1)→ 4,floor(3.9)→ 3
// Calculate total with tax and round to 2 decimals
round(sum({subtotal}, {subtotal} * 0.08), 2)
// Calculate discount percentage
round(({original_price} - {sale_price}) / {original_price} * 100, 1)
Combining Functions
Example 1: Format full name properlyconcat(
upper(substring(trim({first_name}), 0, 1)),
lower(substring(trim({first_name}), 1)),
" ",
upper(substring(trim({last_name}), 0, 1)),
lower(substring(trim({last_name}), 1))
)
// Result: "John Smith" (proper case)
Example 2: Calculate age from birthdate
floor(dateDiff(today(), {birth_date}) / 365.25)
// Result: Age in years
Example 3: Format currency with tax
"$" + round(sum({price}, {price} * {tax_rate}), 2)
// Result: "$125.50"
Advanced Pipe Techniques
Take your pipe skills to the next level with these advanced techniques.
Chaining Pipes
Scenario: Use output from one pipe as input to another. Example: Address standardization- First pipe: Validate and standardize address
- Second pipe: Use standardized address to get geolocation
- Third pipe: Use geolocation to find nearest store
- Store first pipe result in hidden field
- Second pipe uses hidden field as input
- Third pipe uses second pipe's result
- Each pipe triggers the next in sequence
Conditional Pipe Execution
Scenario: Execute different pipes based on user selection. Example: Shipping calculation- If domestic: Use USPS API pipe
- If international: Use FedEx International API pipe
- Country field determines which pipe executes
- Record rule checks country value
- Appropriate pipe triggered based on condition
Error Handling and Fallbacks
Scenario: Provide backup options when API fails. Implementation:- Primary pipe: Try main API
- If fails: Trigger backup pipe with alternative API
- If both fail: Use default values or manual entry
- User notification: Inform user of fallback mode
- Hidden field tracks pipe status
- Record rule checks status field
- Based on status, trigger appropriate action
Caching Pipe Results
Scenario: Avoid repeated API calls for same data. Strategy:- Store pipe results in table
- Check table first before calling API
- Only call API if data not found or expired
- Update cache with new results
- Reduced API costs
- Faster response times
- Less dependent on API availability
- Respect API rate limits
Batch Pipe Operations
Scenario: Process multiple records with pipes. Example: Geocode all customer addresses- Create scheduled task
- Loop through records without coordinates
- For each record, execute geocoding pipe
- Update record with lat/long results
- Track success/failure for each record
- Respect API rate limits (add delays between requests)
- Handle errors gracefully (log failures, retry later)
- Progress tracking (update status field)
- Resume capability (if process interrupted)
Practical Examples
Let's put everything together with complete, real-world examples.
Example 1: Order Form with Dynamic Pricing
Form fields:- Product (dropdown)
- Quantity (number)
- Destination zip code (text)
- Shipping method (dropdown: Standard, Express, Overnight)
- Subtotal (calculated, read-only)
- Shipping cost (from pipe, read-only)
- Tax (calculated, read-only)
- Total (calculated, read-only)
- Product pricing pipe:
- Trigger: Product selection
- Gets current price and stock
- Updates subtotal:
price * quantity
- Shipping calculation pipe:
- Trigger: Zip code or method change
- Sends: product weight, destination, method
- Returns: shipping cost
- Tax calculation pipe:
- Trigger: Zip code change
- Gets: Tax rate for destination
- Calculates:
(subtotal + shipping) * tax_rate
total = subtotal + shipping_cost + tax_amount
Example 2: Customer Registration with Validation
Form fields:- Email (text with validation)
- Company name (text)
- Tax ID (text)
- Phone number (text)
- Address fields (street, city, state, zip)
- Email verification:
- Checks if email exists and is deliverable
- Prevents duplicate registrations
- Shows checkmark or error
- Company lookup:
- Searches business registry by Tax ID
- Auto-populates company name if found
- Validates business is active
- Phone validation:
- Formats phone number
- Verifies number is valid
- Identifies carrier and phone type
- Address standardization:
- Validates address exists
- Standardizes format (USPS guidelines)
- Adds missing elements (ZIP+4)
- Real-time feedback as user fills form
- Green checkmarks for validated fields
- Red errors for invalid data
- Auto-completion reduces typing
- Form submission only allowed when all validations pass
Example 3: Event Registration with Availability Check
Form fields:- Event (dropdown)
- Number of attendees (number)
- Session preference (dropdown - dynamic)
- Meal choice (dropdown)
- Special requirements (text)
- Event details pipe:
- Gets: Event date, location, capacity, price
- Displays: Event information
- Checks: Registration deadline
- Availability check pipe:
- Checks: Current registrations vs. capacity
- Returns: Available spots
- Updates: Real-time as others register
- Session options pipe:
- Loads: Available sessions for selected event
- Shows: Session capacity and availability
- Filters: Only sessions with available space
- Price calculation pipe:
- Calculates:
base_price * attendees - Applies: Early bird discounts if applicable
- Adds: Meal upgrade costs
- Calculates:
- User selects event
- Pipe loads event details and checks availability
- If spots available, show registration form
- User enters number of attendees
- Pipe validates sufficient capacity
- Load available sessions
- Calculate total price
- Allow registration if all validations pass
Troubleshooting Common Issues
When working with pipes, you may encounter these common issues:
Pipe Not Executing
Symptoms: Pipe doesn't run when expected. Possible causes:- Trigger not configured correctly
- Required field values missing
- Field slug mismatch in configuration
- Conditional logic preventing execution
- Check trigger settings (onChange, onBlur, etc.)
- Verify all parameter fields have values
- Review field slugs match exactly
- Test with simplified conditions first
Incorrect Results
Symptoms: Pipe returns wrong data or empty values. Possible causes:- Incorrect JSON path expression
- API response structure different than expected
- Parameter values not mapping correctly
- Data type mismatch
- Use pipe tester to inspect API response
- Verify JSON path matches actual response structure
- Check parameter mapping in pipe configuration
- Ensure data types are compatible
Slow Performance
Symptoms: Form becomes sluggish when pipes execute. Possible causes:- External API is slow
- Too many pipes executing simultaneously
- Large response data being processed
- Network latency
- Add loading indicators to manage user expectations
- Optimize trigger timing (use onBlur instead of onChange)
- Cache frequently accessed data
- Consider async processing for non-critical data
Authentication Errors
Symptoms: 401 or 403 errors in pipe logs. Possible causes:- Invalid API key
- Expired token
- Incorrect authentication header format
- Insufficient API permissions
- Verify API key is correct and active
- Check token expiration and refresh if needed
- Review API documentation for correct auth format
- Confirm API key has necessary permissions
Best Practices
Follow these best practices for effective pipe implementation:
Design
- Single responsibility: Each pipe should do one thing well
- Descriptive names: Name pipes clearly to indicate their purpose
- Documentation: Add descriptions explaining what each pipe does
- Reusability: Create generic pipes that can be reused
Performance
- Minimize calls: Only execute pipes when necessary
- Appropriate triggers: Use onBlur instead of onChange for expensive operations
- Cache results: Store frequently accessed data
- Async when possible: Don't block user interface
User Experience
- Loading indicators: Show when pipes are executing
- Clear feedback: Indicate success or failure
- Error messages: User-friendly error descriptions
- Fallback options: Provide alternatives if pipe fails
Security
- Protect API keys: Never expose in client-side code
- Validate inputs: Sanitize all user input before sending to APIs
- Validate outputs: Don't trust external data blindly
- Use HTTPS: Always use encrypted connections
Maintenance
- Monitor logs: Regularly review pipe execution logs
- Test regularly: Verify pipes still work as expected
- Update documentation: Keep pipe descriptions current
- Version APIs: Be aware of API changes and updates
Hands-On Exercise
Create a comprehensive form using multiple pipes:
Exercise: Contact Form with Enrichment
Objective: Build a contact form that uses pipes to validate and enrich user input. Required fields:- Email address
- Company website
- Company name (auto-populated)
- Industry (auto-populated)
- Company size (auto-populated)
- Phone number
- Job title
- Email validation pipe
- Verify email is valid and deliverable
- Show checkmark or error icon
- Company enrichment pipe
- Extract domain from email
- Look up company information
- Populate company fields automatically
- Phone formatting pipe
- Format phone number consistently
- Validate phone number
- All pipes execute correctly
- Fields auto-populate when possible
- Validation provides clear feedback
- Form only submits when all validations pass
Next Steps
You now have practical experience implementing pipes in forms and components. The next article introduces webhooks—another powerful integration method that enables real-time, event-driven communication between Tadabase and external systems.
While pipes are great for pulling data into Tadabase on demand, webhooks excel at pushing data out when specific events occur, and receiving data from external systems when they're ready to send it.
Key Takeaways
Remember these essential concepts:
- Pipes in forms: Load external data, validate input, calculate values dynamically
- Triggers: Choose appropriate triggers (onChange, onBlur, onSubmit)
- Tadabase functions: Use built-in text, date, and number functions for data manipulation
- Validation: Implement real-time validation with external APIs
- User experience: Provide feedback during pipe execution
- Error handling: Gracefully handle pipe failures
- Performance: Optimize pipe execution to maintain responsiveness
- Testing: Thoroughly test all pipe scenarios before production
Next: Article 7.4 - Webhooks Overview
We'd love to hear your feedback.