Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Sunday, June 1
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Generate own code for Apex using Salesforce CLI

    Generate own code for Apex using Salesforce CLI

    Dhanik Lal SahniBy Dhanik Lal SahniJune 7, 2020Updated:January 13, 2025No Comments5 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Generate own code for Apex using Salesforce CLI
    Share
    Facebook Twitter LinkedIn Pinterest Email

    While working with product development in Salesforce, We implement lot of development process like code guidelines process, code review process, release management process, org management process etc. This process help us in stream line our development and release process.

    In development process we also want that all developer follow same type of code practice in complete application. We can share development guide with each developer to use same practice but it is followed or not it is difficult to find in initial stage. We will get to know only when we get code review request. So might be possible it is too late to change code which developer has written.

    So it will be better we generate basic code structure when they create apex, trigger or selector class. So that developer know how they have to implement code. Let us see how we can create basic code using template from Salesforce CLI.

    What is Salesforce CLI?

    The Salesforce CLI is a powerful command line interface that simplifies development and build automation when working with your Salesforce org.

    Prerequisites for CLI development

    1. NodeJS
    2. Salesforce CLI
    3. NPM user (to publish in NPM)

    Steps for creating Salesforce CLI

    1. Generate Salesforce CLI
    2. Link plugin with Salesforce DX
    3. Publish Your Plugin

    1. Generate Salesforce CLI

    First we have to generate code structure for Salesforce CLI development. We can do this by running command sfdx plugins:generate command.

    sfdx plugins:generate salesforcecodex-dx-plugin

    This command will generate salesforcecodex-dx-plugin plugin. It will ask series of question when you enter above command. You can just press enter to take default values.

    SalesforceCodex – Default Plugin Code Structure

    By default it will generate hello:org command. Let us create our own command structure for code template.

    We want to use command scdx:code:create for our plugin. So create scdx\code folder under folder command and create typescript file create.ts .

    Salesforce Plugin Structure | Salesforce CLI
    SalesforceCodex – Custom Code Plugin Structure

    This typescript file create.ts has all code related to plugin logic. We need to generate apex class, trigger and selector class so we have to write logic to create file in type script. We can use below code to create file in type script.

    import * as fs from 'fs';
    import * as fse from 'fs-extra';
    import * as path from 'path';
    
    const newFilePath = path.dirname(newFile);
    fse.ensureDirSync(newFilePath);
    fs.writeFileSync(newFile, content);
    filesCreated.push(newFile);

    Template Code:

    As we need to generate apex code so we need to add template code for apex, trigger and selector class. You can use any other template as well, as per your requirement.

    Let us take example we want to create apex class AccountService. So by default below files will be created

    1. AccountService.cls
    2. AccountService.cls-meta.xml
    3. AccountServiceTest.cls
    4. AccountServiceTest.cls-meta.xml

    These files will be created based on our configuration in def.js file which will be available in all template folder.

    {
        "vars": [
          "apiVersion",
          "objectName",
          "entityName"
        ],
        "files": [
          ["apex.cls", ".cls"],
          ["apexTest.cls", "Test.cls"],
          ["apex.cls-meta.xml", ".cls-meta.xml"],
          ["apexTest.cls-meta.xml", "Test.cls-meta.xml"]
        ],
        "bundle": false
      }

    vars array has all variable which will be replaced while code generation. See below apex template code which has objectName variable. This variable is replaced when code is generated with provided values.

    files array has all files detail which will be generated when apex class will be generated. It is key value pair array, which says that when we apex.cls will be created then add provided apex class and extension will be .cls .

    Apex Template Code

    In below apex template code, objectName is replaced at runtime while code generation.

    Trigger Template Code:

    In this trigger template code objectName and entityName is replaced at runtime when code is generated.

    How code files are generated?

    Code files are generated based on provided command parameters. Let us see below command which could be provided by developer

    sfdx scdx:code:create -t trigger  -d ./test/t1 -v apiVersion=48.0,objectName=Brand__c     

    Parameter:

    -t – indicate which type of code is created eg. apex, trigger or selector

    -d – indicate folder where these code files are created. if not provided current folder is used.

    -v -variables for code file generation. apiVersion indicate api version for code file and objectName indicate object for which code need to create code file.

    1. For apex class use name of class like AccountService
    2. For selector and trigger use entity name like Account, Brand__c etc

    Based on template parameter (-t), it will go in template folder (apex, trigger, selector). It checks def.js file which has files and variable details. Based on files attribute of def.js it generate code.

    "files": [
          ["apex.cls", ".cls"],
          ["apexTest.cls", "Test.cls"],
          ["apex.cls-meta.xml", ".cls-meta.xml"],
          ["apexTest.cls-meta.xml", "Test.cls-meta.xml"]
        ],

    Template code is generated based on above configuration. Template apex.cls will be created as another cls file . Name of class file is generated based on parameter variable objectName. If template class file has any variable then it is replaced based on parameter values.

    For trigger scenario, for custom object like Brand__c we should generate file BrandTrigger so plugin will replace __c and other space( ) while name generation.

    Code which generate files:

    2. Link plugin with Salesforce DX

    Once Plugin is developed let us test it . Use command sfdx plugins:link to link plugin with Salesforce DX.

    3. Publish Your Plugin

    Publish your plugin to package registry (npm) so that it can be searched and installed by others. Use command npm publish for publishing it. You will require user in NPMJS.

    Complete Code:

    salesforcecodex-dx-plugin

    References:

    • 1. https://github.com/wadewegner/sfdx-code-gen
    • 2. https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_plugins.meta/sfdx_cli_plugins/cli_plugins_architecture_sf_cli.htm
    • 3. https://trailhead.salesforce.com/live/videos/a2r3k0000014vJw/build-and-release-salesforce-cli-plug-in/
    • 4. https://docs.npmjs.com/cli/publish

    Related Posts

    1. Object Identification using Google Cloud Vision in Salesforce
    2. Logo Recognition using Google Cloud Vision in Salesforce
    3. Google FitBit Integration with Salesforce
    4. Integrate Google API with Salesforce
    5. Audio to Text by Google Speech API in Salesforce Lightning
    6. Extract Text From Images using Google Cloud Vision
    7. Seamless YouTube Video API Integration in Salesforce
    apex cli salesforce salesforce cli
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleGet All Used Custom Metadata Detail
    Next Article Extract License Plate Number from Image In Salesforce
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni9 Mins Read

    10 Salesforce Chrome Extensions to Boost Your Productivity

    June 1, 2025
    By Dhanik Lal Sahni4 Mins Read

    How to Build a Generic Modal Window in Lightning Web Component

    May 26, 2025
    By Dhanik Lal Sahni6 Mins Read

    Top 10 Salesforce Flow Features of Salesforce Summer ’25

    May 11, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code analysis (3) code optimization (8) custom metadata types (5) design principle (9) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (65) lightning-combobox (5) lightning-datatable (10) lightning component (31) Lightning web component (63) lwc (52) named credential (8) news (4) optimize apex code (4) optimize apex trigger (3) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (142) salesforce apex (47) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code analysis (3) code optimization (8) custom metadata types (5) design principle (9) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (65) lightning-combobox (5) lightning-datatable (10) lightning component (31) Lightning web component (63) lwc (52) named credential (8) news (4) optimize apex code (4) optimize apex trigger (3) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (142) salesforce apex (47) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.