LogoLogo
HomeAPIBlog
3.0.0-SNAPSHOT
3.0.0-SNAPSHOT
  • INTRODUCTION
    • Getting Started
      • Running Local Development Servers
      • Beginner Tutorial: Hello World
      • Beginner Tutorial: Hello Database
      • Tutorial: Wheels, AJAX, and You
    • Frameworks and Wheels
    • Requirements
    • Manual Installation
    • Upgrading
    • Screencasts
  • Command Line Tools
    • CLI Overview
    • Quick Start Guide
    • Command Reference
      • Core Commands
        • wheels init
        • wheels info
        • wheels reload
        • wheels deps
        • wheels destroy
        • wheels watch
      • Code Generation
        • wheels generate app
        • wheels generate app-wizard
        • wheels generate controller
        • wheels generate model
        • wheels generate view
        • wheels generate property
        • wheels generate route
        • wheels generate resource
        • wheels generate api-resource
        • wheels generate frontend
        • wheels generate test
        • wheels generate snippets
        • wheels scaffold
      • Database Commands
        • wheels dbmigrate info
        • wheels dbmigrate latest
        • wheels dbmigrate up
        • wheels dbmigrate down
        • wheels dbmigrate reset
        • wheels dbmigrate exec
        • wheels dbmigrate create blank
        • wheels dbmigrate create table
        • wheels dbmigrate create column
        • wheels dbmigrate remove table
        • wheels db schema
        • wheels db seed
      • Testing Commands
        • wheels test
        • wheels test run
        • wheels test coverage
        • wheels test debug
      • Configuration Commands
        • wheels config list
        • wheels config set
        • wheels config env
      • Environment Management
        • wheels env
        • wheels env setup
        • wheels env list
        • wheels env switch
      • Plugin Management
        • wheels plugins
        • wheels plugins list
        • wheels plugins install
        • wheels plugins remove
      • Code Analysis
        • wheels analyze
        • wheels analyze code
        • wheels analyze performance
        • wheels analyze security
      • Security Commands
        • wheels security
        • wheels security scan
      • Performance Commands
        • wheels optimize
        • wheels optimize performance
      • Documentation Commands
        • wheels docs
        • wheels docs generate
        • wheels docs serve
      • CI/CD Commands
        • wheels ci init
      • Docker Commands
        • wheels docker init
        • wheels docker deploy
      • Deployment Commands
        • wheels deploy
        • wheels deploy audit
        • wheels deploy exec
        • wheels deploy hooks
        • wheels deploy init
        • wheels deploy lock
        • wheels deploy logs
        • wheels deploy proxy
        • wheels deploy push
        • wheels deploy rollback
        • wheels deploy secrets
        • wheels deploy setup
        • wheels deploy status
        • wheels deploy stop
    • CLI Development Guides
      • Creating Commands
      • Service Architecture
      • Migrations Guide
      • Testing Guide
  • Working with Wheels
    • Conventions
    • Configuration and Defaults
    • Directory Structure
    • Switching Environments
    • Testing Your Application
    • Using the Test Environment
    • Contributing to Wheels
    • Submitting Pull Requests
    • Documenting your Code
  • Handling Requests with Controllers
    • Request Handling
    • Rendering Content
    • Redirecting Users
    • Sending Files
    • Sending Email
    • Responding with Multiple Formats
    • Using the Flash
    • Using Filters
    • Verification
    • Event Handlers
    • Routing
    • URL Rewriting
      • Apache
      • IIS
      • Tomcat
      • Nginx
    • Obfuscating URLs
    • Caching
    • Nesting Controllers
    • CORS Requests
  • Displaying Views to Users
    • Pages
    • Partials
    • Linking Pages
    • Layouts
    • Form Helpers and Showing Errors
    • Displaying Links for Pagination
    • Date, Media, and Text Helpers
    • Creating Custom View Helpers
    • Localization
  • Database Interaction Through Models
    • Object Relational Mapping
    • Creating Records
    • Reading Records
    • Updating Records
    • Deleting Records
    • Column Statistics
    • Dynamic Finders
    • Getting Paginated Data
    • Associations
    • Nested Properties
    • Object Validation
    • Object Callbacks
    • Calculated Properties
    • Transactions
    • Dirty Records
    • Soft Delete
    • Automatic Time Stamps
    • Database Migrations
      • Migrations in Production
    • Using Multiple Data Sources
  • Plugins
    • Installing and Using Plugins
    • Developing Plugins
    • Publishing Plugins
  • Project Documentation
    • Overview
  • External Links
    • Source Code
    • Issue Tracker
    • Sponsor Us
    • Community
Powered by GitBook
LogoLogo
On this page
  • Synopsis
  • Description
  • Arguments
  • Options
  • Property Syntax
  • Basic Format
  • Supported Types
  • Property Options
  • Examples
  • Add single property
  • Add multiple properties
  • Add text property with validation
  • Add association
  • Add calculated property
  • Generated Code Examples
  • Basic Property Addition
  • Multiple Properties
  • Association Property
  • Calculated Property
  • Migration Generation
  • Migration File
  • Validation Rules
  • Automatic Validations
  • Custom Validations
  • Property Callbacks
  • Complex Properties
  • Enum-like Property
  • File Upload Property
  • JSON Property
  • Property Modifiers
  • Encrypted Property
  • Slugged Property
  • Batch Operations
  • Add Multiple Related Properties
  • Add Timestamped Properties
  • Integration with Existing Code
  • Preserve Existing Structure
  • Conflict Resolution
  • Best Practices
  • Common Patterns
  • Soft Delete
  • Versioning
  • Status Tracking
  • Audit Fields
  • Testing
  • See Also

Was this helpful?

Edit on GitHub
Export as PDF
  1. Command Line Tools
  2. Command Reference
  3. Code Generation

wheels generate property

Add properties to existing model files.

Synopsis

wheels generate property [model] [properties] [options]
wheels g property [model] [properties] [options]

Description

The wheels generate property command adds new properties to existing model files. It can add simple properties, associations, calculated properties, and validations while maintaining proper code formatting and structure.

Arguments

Argument
Description
Default

model

Model name to add properties to

Required

properties

Property definitions (name:type:options)

Required

Options

Option
Description
Default

--migrate

Generate migration for database changes

true

--validate

Add validation rules

true

--defaults

Include default values

false

--callbacks

Generate property callbacks

false

--force

Overwrite without confirmation

false

--help

Show help information

Property Syntax

Basic Format

propertyName:type:option1:option2

Supported Types

  • string - VARCHAR(255)

  • text - TEXT/CLOB

  • integer - INT

  • float - DECIMAL

  • boolean - BIT/BOOLEAN

  • date - DATE

  • datetime - DATETIME

  • timestamp - TIMESTAMP

  • binary - BLOB

Property Options

  • required - Not null

  • unique - Unique constraint

  • index - Create index

  • default=value - Default value

  • limit=n - Character limit

  • precision=n - Decimal precision

  • scale=n - Decimal scale

Examples

Add single property

wheels generate property user email:string:required:unique

Add multiple properties

wheels generate property product "sku:string:required:unique price:float:required stock:integer:default=0"

Add text property with validation

wheels generate property post content:text:required:limit=5000

Add association

wheels generate property order userId:integer:required:belongsTo=user

Add calculated property

wheels generate property user "fullName:calculated"

Generated Code Examples

Basic Property Addition

Before:

component extends="Model" {
    
    function init() {
        // Existing code
    }
    
}

After:

component extends="Model" {
    
    function init() {
        // Existing code
        
        // Properties
        property(name="email", sql="email");
        
        // Validations
        validatesPresenceOf(properties="email");
        validatesUniquenessOf(properties="email");
        validatesFormatOf(property="email", regEx="^[^@\s]+@[^@\s]+\.[^@\s]+$");
    }
    
}

Multiple Properties

Command:

wheels generate property product "name:string:required description:text price:float:required:default=0.00 inStock:boolean:default=true"

Generated:

component extends="Model" {
    
    function init() {
        // Properties
        property(name="name", sql="name");
        property(name="description", sql="description");
        property(name="price", sql="price", default=0.00);
        property(name="inStock", sql="in_stock", default=true);
        
        // Validations
        validatesPresenceOf(properties="name,price");
        validatesNumericalityOf(property="price", allowBlank=false, greaterThanOrEqualTo=0);
    }
    
}

Association Property

Command:

wheels generate property comment "userId:integer:required:belongsTo=user postId:integer:required:belongsTo=post"

Generated:

component extends="Model" {
    
    function init() {
        // Associations
        belongsTo(name="user", foreignKey="userId");
        belongsTo(name="post", foreignKey="postId");
        
        // Properties
        property(name="userId", sql="user_id");
        property(name="postId", sql="post_id");
        
        // Validations
        validatesPresenceOf(properties="userId,postId");
    }
    
}

Calculated Property

Command:

wheels generate property user fullName:calculated --callbacks

Generated:

component extends="Model" {
    
    function init() {
        // Properties
        property(name="fullName", sql="", calculated=true);
    }
    
    // Calculated property getter
    function getFullName() {
        return this.firstName & " " & this.lastName;
    }
    
}

Migration Generation

When --migrate=true (default), generates migration:

Migration File

db/migrate/[timestamp]_add_properties_to_[model].cfc:

component extends="wheels.migrator.Migration" hint="Add properties to product" {

    function up() {
        transaction {
            addColumn(table="products", columnName="sku", columnType="string", limit=50, null=false);
            addColumn(table="products", columnName="price", columnType="decimal", precision=10, scale=2, null=false, default=0.00);
            addColumn(table="products", columnName="stock", columnType="integer", null=true, default=0);
            
            addIndex(table="products", columnNames="sku", unique=true);
        }
    }
    
    function down() {
        transaction {
            removeIndex(table="products", columnNames="sku");
            removeColumn(table="products", columnName="stock");
            removeColumn(table="products", columnName="price");
            removeColumn(table="products", columnName="sku");
        }
    }

}

Validation Rules

Automatic Validations

Based on property type and options:

Type
Validations Applied

string:required

validatesPresenceOf, validatesLengthOf

string:unique

validatesUniquenessOf

email

validatesFormatOf with email regex

integer

validatesNumericalityOf(onlyInteger=true)

float

validatesNumericalityOf

boolean

validatesInclusionOf(list="true,false,0,1")

date

validatesFormatOf with date pattern

Custom Validations

Add custom validation rules:

wheels generate property user "age:integer:min=18:max=120"

Generated:

validatesNumericalityOf(property="age", greaterThanOrEqualTo=18, lessThanOrEqualTo=120);

Property Callbacks

Generate with callbacks:

wheels generate property user lastLoginAt:datetime --callbacks

Generated:

function init() {
    // Properties
    property(name="lastLoginAt", sql="last_login_at");
    
    // Callbacks
    beforeUpdate("updateLastLoginAt");
}

private function updateLastLoginAt() {
    if (hasChanged("lastLoginAt")) {
        // Custom logic here
    }
}

Complex Properties

Enum-like Property

wheels generate property order "status:string:default=pending:inclusion=pending,processing,shipped,delivered"

Generated:

property(name="status", sql="status", default="pending");
validatesInclusionOf(property="status", list="pending,processing,shipped,delivered");

File Upload Property

wheels generate property user "avatar:string:fileField"

Generated:

property(name="avatar", sql="avatar");

// In the init() method
afterSave("processAvatarUpload");
beforeDelete("deleteAvatarFile");

private function processAvatarUpload() {
    if (hasChanged("avatar") && isUploadedFile("avatar")) {
        // Handle file upload
    }
}

JSON Property

wheels generate property user "preferences:text:json"

Generated:

property(name="preferences", sql="preferences");

function getPreferences() {
    if (isJSON(this.preferences)) {
        return deserializeJSON(this.preferences);
    }
    return {};
}

function setPreferences(required struct value) {
    this.preferences = serializeJSON(arguments.value);
}

Property Modifiers

Encrypted Property

wheels generate property user "ssn:string:encrypted"

Generated:

property(name="ssn", sql="ssn");

beforeSave("encryptSSN");
afterFind("decryptSSN");

private function encryptSSN() {
    if (hasChanged("ssn") && Len(this.ssn)) {
        this.ssn = encrypt(this.ssn, application.encryptionKey);
    }
}

private function decryptSSN() {
    if (Len(this.ssn)) {
        this.ssn = decrypt(this.ssn, application.encryptionKey);
    }
}

Slugged Property

wheels generate property post "slug:string:unique:fromProperty=title"

Generated:

property(name="slug", sql="slug");
validatesUniquenessOf(property="slug");

beforeValidation("generateSlug");

private function generateSlug() {
    if (!Len(this.slug) && Len(this.title)) {
        this.slug = createSlug(this.title);
    }
}

private function createSlug(required string text) {
    return reReplace(
        lCase(trim(arguments.text)),
        "[^a-z0-9]+",
        "-",
        "all"
    );
}

Batch Operations

Add Multiple Related Properties

wheels generate property user "
    profile.bio:text
    profile.website:string
    profile.twitter:string
    profile.github:string
" --nested

Add Timestamped Properties

wheels generate property post "publishedAt:timestamp deletedAt:timestamp:nullable"

Integration with Existing Code

Preserve Existing Structure

The command intelligently adds properties without disrupting:

  • Existing properties

  • Current validations

  • Defined associations

  • Custom methods

  • Comments and formatting

Conflict Resolution

wheels generate property user email:string
> Property 'email' already exists. Options:
> 1. Skip this property
> 2. Update existing property
> 3. Add with different name
> Choice:

Best Practices

  1. Add properties incrementally

  2. Always generate migrations

  3. Include appropriate validations

  4. Use semantic property names

  5. Add indexes for query performance

  6. Consider default values carefully

  7. Document complex properties

Common Patterns

Soft Delete

wheels generate property model deletedAt:timestamp:nullable

Versioning

wheels generate property document "version:integer:default=1 versionedAt:timestamp"

Status Tracking

wheels generate property order "status:string:default=pending statusChangedAt:timestamp"

Audit Fields

wheels generate property model "createdBy:integer:belongsTo=user updatedBy:integer:belongsTo=user"

Testing

After adding properties:

# Run migration
wheels dbmigrate up

# Generate property tests
wheels generate test model user

# Run tests
wheels test

See Also

Previouswheels generate viewNextwheels generate route

Last updated 2 days ago

Was this helpful?

- Generate models

- Create columns

- Generate tests

wheels generate model
wheels dbmigrate create column
wheels generate test