### Install FormCraft NuGet Packages
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
Instructions to add FormCraft and FormCraft.ForMudBlazor NuGet packages to a Blazor project using the .NET CLI. These packages provide the core library and MudBlazor integration respectively.
```bash
dotnet add package FormCraft
dotnet add package FormCraft.ForMudBlazor
```
--------------------------------
### Configure FormCraft Services in Program.cs
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
Add required MudBlazor and FormCraft services to the Blazor application's service collection in `Program.cs`. This step is crucial for dependency injection and making FormCraft functionalities available throughout the application.
```csharp
// Add MudBlazor services
builder.Services.AddMudServices();
// Add FormCraft services
builder.Services.AddFormCraft();
builder.Services.AddFormCraftMudBlazor();
```
--------------------------------
### Installing git-cliff for Local Development
Source: https://github.com/phmatray/formcraft/blob/main/build/README.md
Provides instructions for manually installing `git-cliff` on Windows (using Scoop) and macOS (using Homebrew) for local changelog generation, in cases where automatic installation is not feasible.
```powershell
# Windows (using Scoop)
scoop install git-cliff
# Or download from GitHub releases
# https://github.com/orhun/git-cliff/releases
```
```bash
# macOS
brew install git-cliff
```
--------------------------------
### Include MudBlazor CSS and JS in HTML
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
Add MudBlazor stylesheet and JavaScript references to the main HTML file (e.g., `index.html` for WebAssembly or `_Host.cshtml` for Server-side Blazor). This ensures proper styling and interactive functionality for MudBlazor components used by FormCraft.
```html
```
--------------------------------
### FormCraft Validation with FluentValidation
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
Demonstrates how to apply custom validation rules to form fields using FormCraft's integration with FluentValidation. This example shows setting minimum length and adding a custom predicate validator for a password field.
```csharp
.AddField(x => x.Password, field => field
.WithLabel("Password")
.Required("Password is required")
.WithMinLength(8, "Password must be at least 8 characters")
.WithValidator(value => value.Any(char.IsDigit), "Password must contain a number"))
```
--------------------------------
### FormCraft Fluent API: Common Field Extension Methods
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
Lists convenience extension methods provided by FormCraft for quickly adding common field types with built-in validation. These methods simplify form configuration by abstracting common patterns.
```APIDOC
- AddRequiredTextField() - Text input with required validation
- AddEmailField() - Email input with format validation
- AddNumericField() - Number input with range validation
- AddDropdownField() - Select dropdown with options
- AddPasswordField() - Password input with strength validation
- AddPhoneField() - Phone number input with format validation
- AddDateField() - Date picker
- AddCheckboxField() - Boolean checkbox
- AddFileUploadField() - File upload control
```
--------------------------------
### Implement Custom Field Renderers in FormCraft
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
This C# example shows how to integrate a custom renderer for a field in FormCraft. It uses the `WithCustomRenderer` method to apply a `ColorPickerRenderer` to the 'Color' field, allowing for specialized UI components beyond standard input types.
```csharp
.AddField(x => x.Color, field => field
.WithLabel("Favorite Color")
.WithCustomRenderer(new ColorPickerRenderer()))
```
--------------------------------
### Define a Data Model for FormCraft
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
Create a simple C# class to serve as the data model for the form. The properties of this model will correspond to the fields in your FormCraft form, enabling type-safe data binding.
```csharp
public class ContactModel
{
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public string Email { get; set; } = "";
public int Age { get; set; };
public string Country { get; set; } = "";
public string Message { get; set; } = "";
}
```
--------------------------------
### Add FormCraft and MudBlazor References to _Imports.razor
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
Include necessary `using` directives for FormCraft and MudBlazor namespaces in `_Imports.razor`. This makes their components and types globally available in all Blazor components without needing explicit `using` statements in each file.
```razor
@using FormCraft
@using FormCraft.ForMudBlazor
@using MudBlazor
```
--------------------------------
### Running the FormCraft Demo Application
Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md
Instructions to navigate to the FormCraft demo Blazor application directory and launch it locally, typically accessible via a secure HTTPS endpoint.
```bash
cd FormCraft.DemoBlazorApp
dotnet run
```
--------------------------------
### Display FormCraft Component in Blazor Page
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
Integrate the configured FormCraft form into a Blazor page using the `FormCraftComponent`. This component binds the model, applies the defined configuration, and handles form submission via the `OnValidSubmit` event.
```razor
@page "/contact"
Contact Form
```
--------------------------------
### Build FormCraft Configuration with Fluent API
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
Demonstrates how to use FormCraft's fluent API (`FormBuilder`) to define form fields, their labels, types, and validation rules for a given model. This code snippet shows how to set up various field types including text, email, numeric, dropdown, and textarea.
```csharp
@code {
private ContactModel model = new();
private IFormConfiguration formConfig;
protected override void OnInitialized()
{
formConfig = FormBuilder
.Create()
.AddRequiredTextField(x => x.FirstName, "First Name", minLength: 2)
.AddRequiredTextField(x => x.LastName, "Last Name", minLength: 2)
.AddEmailField(x => x.Email)
.AddNumericField(x => x.Age, "Age", min: 18, max: 100)
.AddDropdownField(x => x.Country, "Country",
("US", "United States"),
("CA", "Canada"),
("UK", "United Kingdom"))
.AddField(x => x.Message, field => field
.WithLabel("Message")
.AsTextArea(lines: 5)
.Required("Please enter a message"))
.Build();
}
private async Task HandleSubmit(ContactModel submittedModel)
{
// Handle form submission
await Task.CompletedTask;
}
}
```
--------------------------------
### FormCraft Fluent API: AddField with Lambda Configuration
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
Illustrates the generic `AddField` method for configuring form fields with custom labels, validation rules, placeholders, and help text using a lambda expression. This provides fine-grained control over individual field properties.
```APIDOC
.AddField(x => x.PropertyName, field => field
.WithLabel("Display Label")
.Required("Custom error message")
.WithPlaceholder("Placeholder text")
.WithHelpText("Help text for users"))
```
--------------------------------
### Setup Git Hook for Automatic Changelog Generation
Source: https://github.com/phmatray/formcraft/blob/main/CONTRIBUTING.md
Commands to install a pre-commit Git hook that automatically generates and stages the CHANGELOG.md file before each commit. This ensures the changelog is always up-to-date with commit history.
```bash
./setup-hooks.sh
```
```powershell
./setup-hooks.ps1
```
--------------------------------
### Quick Start: Running FormCraft Build Targets
Source: https://github.com/phmatray/formcraft/blob/main/build/README.md
Provides basic `bash` commands to run the FormCraft build system's default target (Compile), execute tests, create NuGet packages, and generate the changelog.
```bash
# Run default target (Compile)
./build.sh
# Run tests
./build.sh Test
# Create NuGet packages
./build.sh Pack
# Generate changelog
./build.sh Changelog
```
--------------------------------
### Set Up EditForm for FormCraft Validation
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Illustrates the correct setup of a Blazor `EditForm` component, including `DataAnnotationsValidator` and `DynamicFormValidator`, to enable comprehensive form validation.
```html
```
--------------------------------
### Building FormCraft Projects
Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md
Provides commands for restoring dependencies, building the FormCraft project in various configurations (debug, release), and packaging it into local NuGet packages for distribution or testing.
```bash
dotnet restore
dotnet build
dotnet build --configuration Release
./pack-local.sh # macOS/Linux
./pack-local.ps1 # Windows
```
--------------------------------
### Verify Git-Cliff Installation
Source: https://github.com/phmatray/formcraft/blob/main/build/README.md
Executes the installed git-cliff command with the '--version' flag to confirm that the executable is correctly installed, accessible in the system's PATH, and to display its current version number.
```bash
git-cliff --version
```
--------------------------------
### Adding a Custom Field Renderer in FormCraft
Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md
Example C# code demonstrating how to implement a custom field renderer by inheriting from `CustomFieldRendererBase` and registering it, enabling the rendering of custom data types or UI components within FormCraft.
```csharp
public class MyCustomRenderer : CustomFieldRendererBase
{
protected override RenderFragment RenderField(IFieldRenderContext context)
{
// Return RenderFragment with MudBlazor components
}
}
// Register in DI or use inline:
.WithCustomRenderer(new MyCustomRenderer())
```
--------------------------------
### Creating Reusable FormCraft Field Configurations
Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md
C# example illustrating the creation of reusable field configurations using extension methods on `FormBuilder`, allowing for consistent and concise definition of common form fields across multiple forms.
```csharp
public static class MyFormExtensions
{
public static FormBuilder AddCustomField(
this FormBuilder builder,
Expression> propertyExpression)
where TModel : new()
{
return builder.AddField(propertyExpression, field => field
.WithLabel("Custom Label")
.WithPlaceholder("Enter value...")
.Required());
}
}
```
--------------------------------
### Add Parameterless Constructor for FormCraft Models
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Explains that FormCraft's `FormBuilder` often requires a parameterless constructor (`new()`) for models, and provides an example of how to add one if necessary.
```csharp
public class MyModel // Add parameterless constructor if needed
{
public MyModel() { }
}
```
--------------------------------
### Install Git-Cliff on Linux
Source: https://github.com/phmatray/formcraft/blob/main/build/README.md
Downloads the latest git-cliff release for Linux x86_64, extracts the executable from the tarball, and moves it to a common system-wide binary directory (/usr/local/bin) to make it accessible from any location in the terminal.
```bash
wget -qO- https://github.com/orhun/git-cliff/releases/latest/download/git-cliff-x86_64-unknown-linux-gnu.tar.gz | tar -xz
sudo mv git-cliff /usr/local/bin/
```
--------------------------------
### Install FormCraft.ForMudBlazor via .NET CLI
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.ForMudBlazor/README.md
This command adds the FormCraft.ForMudBlazor NuGet package to your project, enabling MudBlazor integration for dynamic forms.
```bash
dotnet add package FormCraft.ForMudBlazor
```
--------------------------------
### Create a User Registration Form with FormCraft in C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/examples.md
Illustrates building a user registration form with FormCraft, showcasing features like username validation (no spaces), email, password with confirmation, date of birth validation (age check), and required terms acceptance.
```csharp
public class RegistrationModel
{
public string Username { get; set; } = "";
public string Email { get; set; } = "";
public string Password { get; set; } = "";
public string ConfirmPassword { get; set; } = "";
public DateTime DateOfBirth { get; set; }
public bool AcceptTerms { get; set; }
}
var config = FormBuilder
.Create()
.AddRequiredTextField(x => x.Username, "Username", minLength: 3, maxLength: 20)
.WithValidator(value => !value.Contains(" "), "Username cannot contain spaces")
.AddEmailField(x => x.Email)
.AddPasswordField(x => x.Password, "Password", 8, true)
.AddField(x => x.ConfirmPassword, field => field
.WithLabel("Confirm Password")
.Required("Please confirm your password")
.WithValidator((value, model) => value == model.Password, "Passwords must match"))
.AddDateField(x => x.DateOfBirth, "Date of Birth")
.WithValidator(value => value < DateTime.Now.AddYears(-13), "Must be at least 13 years old")
.AddCheckboxField(x => x.AcceptTerms, "I accept the terms and conditions")
.Required("You must accept the terms")
.Build();
```
--------------------------------
### Inspect FormCraft Field Configuration at Runtime
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Provides an example of how to inspect the FormCraft field configuration programmatically within a Blazor component's `OnParametersSet` method, useful for debugging field properties and counts.
```csharp
protected override void OnParametersSet()
{
Console.WriteLine($"Form has {Configuration.Fields.Count} fields");
foreach (var field in Configuration.Fields)
{
Console.WriteLine($"Field: {field.FieldName}, Type: {field.GetType()}");
}
}
```
--------------------------------
### Creating a Version Tag for Automated Release Trigger
Source: https://github.com/phmatray/formcraft/blob/main/BUILD_RELEASE_SETUP.md
This command sequence creates a lightweight Git tag with a specified version (e.g., `v1.0.0`) and pushes it to the remote `origin` repository. Pushing a version tag to the main branch is the trigger for the automated CI/CD pipeline to build, test, publish NuGet packages, and create a GitHub release.
```bash
git tag v1.0.0
git push origin v1.0.0
```
--------------------------------
### Integrate MudBlazor theming and custom CSS with FormCraft
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md
Configures MudBlazor services and defines a custom theme to apply consistent styling across FormCraft components. It also shows how to apply custom CSS classes to individual fields and provides an example CSS definition.
```csharp
// In Program.cs
builder.Services.AddMudServices(config =>
{
config.SnackbarConfiguration.PositionClass = Defaults.Classes.Position.BottomLeft;
});
// Custom theme
var theme = new MudTheme()
{
Palette = new PaletteLight()
{
Primary = "#1976d2",
Secondary = "#dc004e",
// ... other colors
}
};
```
```csharp
.AddField(x => x.SpecialField, field => field
.WithCssClass("my-special-field"))
```
```css
.my-special-field {
background: linear-gradient(45deg, #f0f0f0, #ffffff);
border-radius: 8px;
padding: 1rem;
}
```
--------------------------------
### Extend FormCraft's FormBuilder with custom methods in C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md
Shows how to create extension methods for the `FormBuilder` class, allowing developers to add custom field types or pre-configured field setups, thereby enhancing the form building API and promoting reusability.
```csharp
public static class MyFormBuilderExtensions
{
public static FormBuilder AddCurrencyField(
this FormBuilder builder,
Expression> expression,
string label,
string currency = "USD") where TModel : new()
{
return builder.AddField(expression, field => field
.WithLabel(label)
.WithAttribute("currency", currency)
.WithValidator(value => value >= 0, "Amount must be positive"));
}
}
```
--------------------------------
### Install FormCraft NuGet Package
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft/README.md
This command installs the FormCraft NuGet package into your .NET project, making the library available for use in your Blazor application.
```bash
dotnet add package FormCraft
```
--------------------------------
### Conventional Git Commit Message Examples
Source: https://github.com/phmatray/formcraft/blob/main/CONTRIBUTING.md
Illustrates examples of commit messages adhering to the Conventional Commits specification. These examples demonstrate how to categorize changes like new features, bug fixes, and documentation updates for automated changelog generation.
```git
feat: add field groups layout support
fix: resolve null reference in field renderer
docs: update API documentation
```
--------------------------------
### Define Field Dependencies in FormCraft
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md
This C# code demonstrates how to create a field dependency in FormCraft. The 'State' field is made visible only when the 'Country' field is 'US', and its value is cleared if the country changes from 'US', ensuring data consistency based on user input.
```csharp
.AddField(x => x.State, field => field
.WithLabel("State")
.VisibleWhen(model => model.Country == "US")
.DependsOn(x => x.Country, (model, country) => {
if (country != "US") model.State = "";
}))
```
--------------------------------
### Run Blazor WebAssembly Application Locally
Source: https://github.com/phmatray/formcraft/blob/main/BLAZOR_WASM_CONVERSION.md
Instructions to run the converted Blazor WebAssembly application on a local development machine using the .NET CLI. This command navigates to the application directory and starts the development server.
```bash
cd FormCraft.DemoBlazorApp
dotnet run
```
--------------------------------
### Enable Detailed Logging in FormCraft Applications
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Shows how to configure logging in `Program.cs` to a `LogLevel.Debug` level, providing more detailed output for troubleshooting FormCraft application behavior.
```csharp
// In Program.cs
builder.Logging.SetMinimumLevel(LogLevel.Debug);
```
--------------------------------
### Running FormCraft Tests
Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md
Commands to execute unit and integration tests for the FormCraft project, including options to run all tests, specific test projects, with code coverage, or filter tests by class or method name.
```bash
dotnet test
dotnet test FormCraft.UnitTests/FormCraft.UnitTests.csproj
dotnet test --collect:"XPlat Code Coverage"
dotnet test --filter "FullyQualifiedName~FormBuilderTests"
dotnet test --filter "DisplayName~Should_Build_Valid_Configuration"
```
--------------------------------
### Testing FormCraft Build Targets Locally
Source: https://github.com/phmatray/formcraft/blob/main/BUILD_RELEASE_SETUP.md
These commands allow developers to execute specific build targets of the FormCraft project locally using the `build.sh` script. `Compile` builds the project, `Test` runs the unit tests, and `Pack` creates the NuGet packages. This is useful for verifying changes before committing and pushing to the remote repository.
```bash
./build.sh Compile
./build.sh Test
./build.sh Pack
```
--------------------------------
### Configure global FormCraft options in C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md
Demonstrates how to configure global default behaviors for FormCraft, such as the default layout, visibility of required indicators, and validation settings, using the options pattern in `Program.cs`.
```csharp
builder.Services.Configure(options =>
{
options.DefaultLayout = FormLayout.Horizontal;
options.ShowRequiredIndicator = true;
options.RequiredIndicator = "*";
options.ValidateOnFieldChanged = true;
});
```
--------------------------------
### Install FormCraft NuGet Packages
Source: https://github.com/phmatray/formcraft/blob/main/README.md
This snippet provides the `dotnet add package` commands required to install the core FormCraft library and its specific integration package for MudBlazor. Installing these packages is the initial step to incorporate FormCraft into a .NET Blazor project.
```bash
dotnet add package FormCraft
dotnet add package FormCraft.ForMudBlazor
```
--------------------------------
### FormCraft Contributor Quick Start Commands (Bash)
Source: https://github.com/phmatray/formcraft/blob/main/README.md
Provides essential Git and .NET CLI commands for contributors to quickly set up, build, test, and package the FormCraft project locally. This includes cloning the repository, building the solution, running unit tests, and creating a local NuGet package.
```bash
# Clone the repository
git clone https://github.com/phmatray/FormCraft.git
# Build the project
dotnet build
# Run tests
dotnet test
# Create a local NuGet package
./pack-local.sh # or pack-local.ps1 on Windows
```
--------------------------------
### Handle Type Expressions in FormCraft Fields
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Provides examples of correct and incorrect type expressions when defining FormCraft fields, emphasizing the need to match the field's type with the model property's type to avoid casting errors.
```csharp
// Correct
.AddField(x => x.Age, field => field) // where Age is int
// Incorrect - mixing types
.AddField(x => x.Age.ToString(), field => field) // This creates expression issues
```
--------------------------------
### Executing FormCraft NUKE Build System
Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md
Commands to invoke the NUKE build automation system for the FormCraft project, supporting both macOS/Linux and Windows environments for streamlined build processes.
```bash
./build.sh
./build.ps1
```
--------------------------------
### Design a Multi-Section Survey Form with FormCraft in C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/examples.md
Shows how to construct a survey form using FormCraft, featuring numeric fields, checkboxes, text areas, and conditional display of improvement suggestions based on satisfaction level.
```csharp
public class SurveyModel
{
public string Name { get; set; } = "";
public int Satisfaction { get; set; }
public bool WouldRecommend { get; set; }
public string Feedback { get; set; } = "";
public string ImprovementSuggestions { get; set; } = "";
}
var config = FormBuilder
.Create()
.AddRequiredTextField(x => x.Name, "Your Name")
.AddNumericField(x => x.Satisfaction, "Satisfaction (1-10)", 1, 10)
.AddCheckboxField(x => x.WouldRecommend, "Would you recommend us to others?")
.AddField(x => x.Feedback, field => field
.WithLabel("Additional Feedback")
.WithPlaceholder("Tell us about your experience...")
.AsTextArea(rows: 4))
.AddField(x => x.ImprovementSuggestions, field => field
.WithLabel("Suggestions for Improvement")
.AsTextArea(rows: 3)
.VisibleWhen(m => m.Satisfaction < 8))
.Build();
```
--------------------------------
### Implement a Custom FormCraft UI Framework Adapter in C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft/Forms/Rendering/README.md
This C# example illustrates the basic structure for creating a custom UI framework adapter for FormCraft. It shows how to implement the IUIFrameworkAdapter interface, defining the framework name and providing specific renderers for different field types, along with methods for rendering form elements.
```C#
public class MyFrameworkAdapter : IUIFrameworkAdapter
{
public string FrameworkName => "MyFramework";
public IFieldRenderer TextFieldRenderer => new MyTextFieldRenderer();
// ... implement other properties
public RenderFragment RenderForm(RenderFragment content, string? cssClass = null)
{
// Framework-specific form rendering
}
// ... implement other methods
}
```
--------------------------------
### Implement Custom Asynchronous Validation in FormCraft C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/examples.md
Provides an example of implementing a custom asynchronous field validator in FormCraft using C#. It demonstrates how to check username availability against a service and integrate this custom validator into a form field.
```csharp
public class AccountModel
{
public string Username { get; set; } = "";
public string Email { get; set; } = "";
}
// Custom async validator
public class UsernameAvailabilityValidator : IFieldValidator
{
private readonly IUserService _userService;
public UsernameAvailabilityValidator(IUserService userService)
{
_userService = userService;
}
public async Task ValidateAsync(AccountModel model, string value, IServiceProvider services)
{
if (string.IsNullOrEmpty(value))
return ValidationResult.Success();
var isAvailable = await _userService.IsUsernameAvailableAsync(value);
return isAvailable
? ValidationResult.Success()
: ValidationResult.Error("Username is already taken");
}
}
// Usage
var config = FormBuilder
.Create()
.AddField(x => x.Username, field => field
.WithLabel("Username")
.Required()
.WithAsyncValidator())
.Build();
```
--------------------------------
### C# Form Configuration with FormBuilder
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Illustrates how to configure forms using a fluent FormBuilder pattern. This approach promotes readable configuration by grouping related fields, adding clear labels and help text, and defining meaningful validation messages for user input.
```csharp
// Keep configuration readable
var config = FormBuilder
.Create()
// Group related fields
.AddRequiredTextField(x => x.FirstName, "First Name")
.AddRequiredTextField(x => x.LastName, "Last Name")
// Add clear labels and help text
.AddEmailField(x => x.Email)
.WithHelpText("We'll never share your email")
// Use meaningful validation messages
.AddField(x => x.Password, field => field
.Required("Password is required for security")
.WithMinLength(8, "Password must be at least 8 characters"))
.Build();
```
--------------------------------
### Implement Async Validation for FormCraft Performance
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Illustrates how to implement asynchronous validation (`ValidateAsync`) for expensive operations in FormCraft, suggesting techniques like caching or debouncing to improve form responsiveness.
```csharp
public class ExpensiveValidator : IFieldValidator
{
public async Task ValidateAsync(MyModel model, string value, IServiceProvider services)
{
// Use caching, debouncing, or other optimization techniques
return await SomeExpensiveValidation(value);
}
}
```
--------------------------------
### FormCraft Core Architecture and Design Patterns
Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md
Overview of the fundamental design patterns and architectural components within the FormCraft library, including the Fluent Builder for API chaining, the Rendering Pipeline for UI generation, the Pluggable Validation system, and the Reactive Dependency system for field interactions.
```APIDOC
Fluent Builder Pattern:
- Entry point: FormBuilder.Create()
- Field configuration: .AddField(x => x.Property, field => field.WithLabel("Label"))
- Group management: .AddFieldGroup(group => group.AddField(...))
Rendering Pipeline:
- IFieldRendererService: Manages renderer registry
- IFieldRenderer: Interface for each supported type
- Custom renderers can be registered via DI
Validation Architecture:
- Built-in validators: RequiredValidator, CustomValidator, AsyncValidator
- Integration with FluentValidation via DynamicFormValidator
- IFieldValidator: Interface for custom validators
Dependency System:
- Fields can depend on other fields via DependsOn()
- Dependencies trigger visibility/value updates
- Managed through IFieldDependency
```
--------------------------------
### Group FormCraft fields logically in C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md
Demonstrates how to organize form fields into logical groups using the `WithGroup` extension method, which helps in structuring complex forms and improving user experience.
```csharp
.AddField(x => x.PersonalInfo, field => field
.WithGroup("Personal Information"))
.AddField(x => x.ContactInfo, field => field
.WithGroup("Contact Details"))
```
--------------------------------
### Register Default FormCraft Renderers
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Explains the importance of calling `builder.Services.AddFormCraft()` in `Program.cs` to register the default field renderers, which are essential for fields to display correctly.
```csharp
// In Program.cs
builder.Services.AddFormCraft();
```
--------------------------------
### C# Model Design Best Practices
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Demonstrates best practices for C# model design, including the use of descriptive names, proper initialization of collections, appropriate nullability for optional fields, and the application of validation attributes for data integrity.
```csharp
public class WellDesignedModel
{
// Use descriptive names
public string CustomerName { get; set; } = "";
// Initialize collections
public List Tags { get; set; } = new();
// Use appropriate nullability
public DateTime? OptionalDate { get; set; }
// Add validation attributes as backup
[Required]
[EmailAddress]
public string Email { get; set; } = "";
}
```
--------------------------------
### Optimize Field Dependencies in FormCraft
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Advises on keeping logic simple and fast within `DependsOn` callbacks to prevent performance bottlenecks, especially in forms with complex field interdependencies.
```csharp
// Avoid complex dependency chains
.DependsOn(x => x.Field1, (model, value) => {
// Keep logic simple and fast
})
```
--------------------------------
### Build a Contact Form with FormCraft in C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/examples.md
Demonstrates how to create a contact form using FormCraft, including defining the model, setting up a horizontal layout, adding required text fields, email, phone, dropdowns, and conditional visibility for the city field based on country selection.
```csharp
public class ContactModel
{
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public string Email { get; set; } = "";
public string Phone { get; set; } = "";
public string Country { get; set; } = "";
public string City { get; set; } = "";
public bool SubscribeToNewsletter { get; set; }
}
// Form configuration
var config = FormBuilder
.Create()
.WithLayout(FormLayout.Horizontal)
.AddRequiredTextField(x => x.FirstName, "First Name", minLength: 2)
.AddRequiredTextField(x => x.LastName, "Last Name", minLength: 2)
.AddEmailField(x => x.Email)
.AddField(x => x.Phone, field => field
.WithLabel("Phone")
.WithPlaceholder("(555) 123-4567"))
.AddDropdownField(x => x.Country, "Country",
("US", "United States"),
("CA", "Canada"),
("UK", "United Kingdom"))
.AddField(x => x.City, field => field
.WithLabel("City")
.VisibleWhen(m => !string.IsNullOrEmpty(m.Country))
.DependsOn(x => x.Country, (model, country) => {
if (string.IsNullOrEmpty(country)) {
model.City = "";
}
}))
.AddCheckboxField(x => x.SubscribeToNewsletter, "Subscribe to newsletter")
.Build();
```
--------------------------------
### Virtualize Large Forms with FormCraft Grouping
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md
Suggests using field grouping (`WithGroup`) and conditional visibility (`VisibleWhen`) to virtualize large forms, rendering only visible sections to improve performance.
```csharp
// Group fields and render only visible sections
.AddField(x => x.Section1Field, field => field
.WithGroup("Section 1")
.VisibleWhen(model => model.CurrentSection == 1))
```
--------------------------------
### Enforcing FormCraft Code Quality and Linting
Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md
Command to build the FormCraft project with strict code quality checks, treating all compiler warnings as errors to ensure adherence to C# conventions and analyzer rules.
```bash
dotnet build /p:TreatWarningsAsErrors=true
```
--------------------------------
### FormCraft Migration: New Framework-Agnostic Renderer in C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft/Forms/Rendering/README.md
This C# example demonstrates the new framework-agnostic approach for a field renderer in FormCraft. Instead of directly referencing UI framework components, it specifies a ComponentType which is resolved at runtime based on the configured UI framework, promoting loose coupling and extensibility.
```C#
public class StringFieldRenderer : FieldRendererBase
{
protected override Type ComponentType => typeof(StringFieldComponent<>);
}
```
--------------------------------
### Implement Custom Rate Limiting Service in C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/security.md
Provides an example of the `IRateLimitService` interface for implementing a custom rate limiting mechanism, such as one backed by Redis, for distributed environments. This allows for flexible and scalable rate limiting solutions.
```csharp
public class RedisRateLimitService : IRateLimitService
{
private readonly IConnectionMultiplexer _redis;
public async Task CheckRateLimitAsync(
string identifier,
int maxAttempts,
TimeSpan timeWindow)
{
// Redis implementation
}
}
```
--------------------------------
### Implement and register a custom FormCraft field renderer in C#
Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md
Defines a custom field renderer by implementing the `IFieldRenderer` interface to handle specialized input types, and registers it with the dependency injection container for FormCraft to utilize.
```csharp
public class CustomFieldRenderer : IFieldRenderer
{
public bool CanRender(Type fieldType, string? fieldSubType = null)
{
return fieldType == typeof(MyCustomType);
}
public void RenderField(
RenderTreeBuilder builder,
object model,
IFieldConfiguration