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
  • Examples
  • Basic controller
  • Controller with multiple actions
  • RESTful controller
  • API controller
  • Custom actions
  • Generated Code
  • Basic Controller
  • RESTful Controller
  • API Controller
  • View Generation
  • index.cfm
  • Naming Conventions
  • Routes Configuration
  • Traditional Routes
  • RESTful Resources
  • Nested Resources
  • Testing
  • Best Practices
  • Common Patterns
  • Authentication Filter
  • Pagination
  • Search
  • See Also

Was this helpful?

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

wheels generate controller

Generate a controller with actions and optional views.

Synopsis

wheels generate controller [name] [actions] [options]
wheels g controller [name] [actions] [options]

Description

The wheels generate controller command creates a new controller CFC file with specified actions and optionally generates corresponding view files. It supports both traditional and RESTful controller patterns.

Arguments

Argument
Description
Default

name

Controller name (singular or plural)

Required

actions

Comma-separated list of actions

index

Options

Option
Description
Default

--rest

Generate RESTful actions

false

--api

Generate API controller (no views)

false

--force

Overwrite existing files

false

--help

Show help information

Examples

Basic controller

wheels generate controller products

Creates:

  • /controllers/Products.cfc with index action

  • /views/products/index.cfm

Controller with multiple actions

wheels generate controller products index,show,new,create,edit,update,delete

Creates controller with all CRUD actions and corresponding views.

RESTful controller

wheels generate controller products --rest

Automatically generates all RESTful actions:

  • index - List all products

  • show - Show single product

  • new - New product form

  • create - Create product

  • edit - Edit product form

  • update - Update product

  • delete - Delete product

API controller

wheels generate controller api/products --api

Creates:

  • /controllers/api/Products.cfc with JSON responses

  • No view files

Custom actions

wheels generate controller reports dashboard,monthly,yearly,export

Generated Code

Basic Controller

component extends="Controller" {

    function init() {
        // Constructor
    }

    function index() {
        products = model("Product").findAll();
    }

}

RESTful Controller

component extends="Controller" {

    function init() {
        // Constructor
    }

    function index() {
        products = model("Product").findAll();
    }

    function show() {
        product = model("Product").findByKey(params.key);
        if (!IsObject(product)) {
            flashInsert(error="Product not found");
            redirectTo(action="index");
        }
    }

    function new() {
        product = model("Product").new();
    }

    function create() {
        product = model("Product").new(params.product);
        if (product.save()) {
            flashInsert(success="Product created successfully");
            redirectTo(action="index");
        } else {
            renderView(action="new");
        }
    }

    function edit() {
        product = model("Product").findByKey(params.key);
        if (!IsObject(product)) {
            flashInsert(error="Product not found");
            redirectTo(action="index");
        }
    }

    function update() {
        product = model("Product").findByKey(params.key);
        if (IsObject(product) && product.update(params.product)) {
            flashInsert(success="Product updated successfully");
            redirectTo(action="index");
        } else {
            renderView(action="edit");
        }
    }

    function delete() {
        product = model("Product").findByKey(params.key);
        if (IsObject(product) && product.delete()) {
            flashInsert(success="Product deleted successfully");
        } else {
            flashInsert(error="Could not delete product");
        }
        redirectTo(action="index");
    }

}

API Controller

component extends="Controller" {

    function init() {
        provides("json");
    }

    function index() {
        products = model("Product").findAll();
        renderWith(products);
    }

    function show() {
        product = model("Product").findByKey(params.key);
        if (IsObject(product)) {
            renderWith(product);
        } else {
            renderWith({error: "Product not found"}, status=404);
        }
    }

    function create() {
        product = model("Product").new(params.product);
        if (product.save()) {
            renderWith(product, status=201);
        } else {
            renderWith({errors: product.allErrors()}, status=422);
        }
    }

    function update() {
        product = model("Product").findByKey(params.key);
        if (IsObject(product) && product.update(params.product)) {
            renderWith(product);
        } else {
            renderWith({errors: product.allErrors()}, status=422);
        }
    }

    function delete() {
        product = model("Product").findByKey(params.key);
        if (IsObject(product) && product.delete()) {
            renderWith({message: "Product deleted"});
        } else {
            renderWith({error: "Could not delete"}, status=400);
        }
    }

}

View Generation

Views are automatically generated for non-API controllers:

index.cfm

<h1>Products</h1>

<p>#linkTo(text="New Product", action="new")#</p>

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <cfloop query="products">
            <tr>
                <td>#products.name#</td>
                <td>
                    #linkTo(text="Show", action="show", key=products.id)#
                    #linkTo(text="Edit", action="edit", key=products.id)#
                    #linkTo(text="Delete", action="delete", key=products.id, method="delete", confirm="Are you sure?")#
                </td>
            </tr>
        </cfloop>
    </tbody>
</table>

Naming Conventions

  • Controller names: PascalCase, typically plural (Products, Users)

  • Action names: camelCase (index, show, createProduct)

  • File locations:

    • Controllers: /controllers/

    • Nested: /controllers/admin/Products.cfc

    • Views: /views/{controller}/

Routes Configuration

Add routes in /config/routes.cfm:

Traditional Routes

<cfset get(name="products", to="products##index")>
<cfset get(name="product", to="products##show")>
<cfset post(name="products", to="products##create")>

RESTful Resources

<cfset resources("products")>

Nested Resources

<cfset namespace("api")>
    <cfset resources("products")>
</cfset>

Testing

Generate tests alongside controllers:

wheels generate controller products --rest
wheels generate test controller products

Best Practices

  1. Use plural names for resource controllers

  2. Keep controllers focused on single resources

  3. Use --rest for standard CRUD operations

  4. Implement proper error handling

  5. Add authentication in init() method

  6. Use filters for common functionality

Common Patterns

Authentication Filter

function init() {
    filters(through="authenticate", except="index,show");
}

private function authenticate() {
    if (!session.isLoggedIn) {
        redirectTo(controller="sessions", action="new");
    }
}

Pagination

function index() {
    products = model("Product").findAll(
        page=params.page ?: 1,
        perPage=25,
        order="createdAt DESC"
    );
}

Search

function index() {
    if (StructKeyExists(params, "q")) {
        products = model("Product").findAll(
            where="name LIKE :search OR description LIKE :search",
            params={search: "%#params.q#%"}
        );
    } else {
        products = model("Product").findAll();
    }
}

See Also

Previouswheels generate app-wizardNextwheels generate model

Last updated 2 days ago

Was this helpful?

- Generate models

- Generate views

- Generate complete CRUD

- Generate controller tests

wheels generate model
wheels generate view
wheels scaffold
wheels generate test