---
title: Soft Limit Function on a Craft CMS Text Field Using a Module
date: 2022-10-25T17:00:00+01:00
author: John Henry Donovan
canonical_url: "https://johnhenry.ie/blog/2022/10/soft-limit-function-on-a-craft-cms-text-field-using-a-module"
section: Blog
---
Browse by categoryAll PostsWeb DevelopmentDesignLifestyleMusic &amp; FilmTutorialsSpottedSpeakingReviewsFound FoodRecipesIreland

[](/blog)

# Soft Limit Function On A Craft CMS Text Field Using A Module

Posted on 25th October, 2022

A short tutorial showing how to add a soft limit on characters for a Craft CMS text field. We use a module to achieve this functionally without using a plugin. A module is a great way to include website/client-centric logic in Craft CMS.

![Screenshot 2022 10 25 171529 2022 10 25 161908 hrss](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAFCAIAAACreXkmAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAZElEQVQYlbVRQQ7AIAhrE///Y9IdKAwXt9tMEAKlBaUk/HCadW0CgvClR7IiWzfaVPwtEBEbICP7SjcZW+WORl3D7JZBAiiA3oKZATTnfNnmDFGxPv+gn2mvMK8c/EhqfC3v5gsfkD/qBh5xPwAAAABJRU5ErkJggg==)

## Set up module structure

Inside your Craft CMS project’s root create the following directory structure for the new module, along with the main module class `SiteModule.php`.

```treeview
modules
├─── Module.php
└─── sitemodule/
    └─── src/
        ├─── SiteModule.php
        └─── assets/
            ├─── SiteAssets.php
            └─── js/
                └─── site.js
```

## Set up class autoloading

Tell Composer how to find your module’s classes by setting the [`autoload`](https://getcomposer.org/doc/04-schema.md#autoload) field in your project’s `composer.json` file.

```javascript
"autoload": {
    "psr-4": {
      "modules\\sitemodule\\": "modules/sitemodule/src/"
    }
  },
```

composer.json

With that in place, go to your project’s directory in your terminal, and run the following command:

```twig
composer dump-autoload -a
```

That will tell Composer to update its class autoloader script based on your new `autoload` mapping.

## Update the application config

We can then add the module to your project’s [application configuration](https://craftcms.com/docs/4.x/config/#application-configuration) by listing it in the *modules* and *bootstrap* arrays. This can be done by editing the project’s `config/app.php` file:

```php
<?php

use craft\helpers\App;

return [
    'id' => App::env('APP_ID') ?: 'CraftCMS',
    'modules' => [
        'site-module' => \modules\sitemodule\SiteModule::class,
    ],
    'bootstrap' => ['site-module'],
];
```

config/app.php

## The main module class

The `SiteModule.php` file is your module’s entry point for the system. Its `init()` method is the best place to register event listeners, and any other steps it needs to take to initialize itself. Add the following code to your `SiteModule.php` file.

```php
<?php
namespace modules\sitemodule;

use modules\sitemodule\assets\SiteAssets;

use Craft;
use craft\events\TemplateEvent;
use craft\web\View;

use yii\base\Event;
use yii\base\Module;
class SiteModule extends Module
{
    public function init(): void
    {

        parent::init();

        Craft::setAlias('@sitemodule', __DIR__);

        if (Craft::$app->getRequest()->getIsCpRequest()) {
            Event::on(
                View::class,
                View::EVENT_BEFORE_RENDER_TEMPLATE,
                function (TemplateEvent $event) {
                    Craft::$app->getView()->registerAssetBundle(SiteAssets::class);
                }
            );
        }

    }
}
```

modules/sitemodule/src/SiteModule.php

## Create an Asset Bundle

We then create an [Asset Bundle](https://craftcms.com/docs/4.x/extend/asset-bundles.html#setting-it-up) so we can register specific CSS and JS files Add the following asset bundle to your `SiteAssets.php` file.

```php
<?php
namespace modules\sitemodule\assets;

use craft\web\AssetBundle;
use craft\web\assets\cp\CpAsset;

class SiteAssets extends AssetBundle
{

    public function init(): void
    {
        $this->sourcePath = '@sitemodule/assets';

        $this->depends = [
            CpAsset::class,
        ];

        $this->js = [
            'js/site.js',
        ];

        parent::init();
    }
}
```

modules/sitemodule/src/assets/SiteAssets.php

## Soft Limit JavaScript

So inside of the `site.js` is where we add our JavaScript for our soft limit functionality. We specifically target `field-summary` in my example. `summary` being the handle of the text field we are limiting. Original CodePen [https://​codepen​.io/​s​t​a​m​d​/​pen/B…](https://codepen.io/stamd/pen/BaJJrdq)

```javascript
let textArea = document.getElementById("fields-summary");
let characterCounter = document.createElement('span');
characterCounter.textContent = '250/250';

const maxNumOfChars = 250;

function insertAfter(referenceNode, newNode) {
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

if (textArea) {
  insertAfter(textArea, characterCounter);

  const countCharacters = () => {
    let numOfEnteredChars = textArea.value.length;
    let counter = maxNumOfChars - numOfEnteredChars;
    characterCounter.textContent = counter + "/250";
    if (counter < 0) {
      characterCounter.style.color = "red";
    } else if (counter < 20) {
      characterCounter.style.color = "orange";
    } else {
      characterCounter.style.color = "black";
    }
  };
  window.addEventListener('load', countCharacters, false);
  textArea.addEventListener("input", countCharacters, false);
}
```

modules/sitemodule/src/assets/js/site.js

## Resources

- [https://​craftcms​.com/​d​o​c​s​/4.x/…](https://craftcms.com/docs/4.x/extend/module-guide.html)
- [https://​craftquest​.io/​c​o​u​r​s​e​s​/​m​y​-​f​i​r​s​t​-​c​r​a​f​t​-​c​m​s​-​m​odule](https://craftquest.io/courses/my-first-craft-cms-module)
- [https://​doublesecretagency​.github​.io/​c​r​a​f​t​-​b​u​s​i​n​e​s​s​l​ogic/](https://doublesecretagency.github.io/craft-businesslogic/)
- [https://​nystudio107​.com/​b​l​o​g​/​e​n​h​a​n​c​i​n​g​-​a​-​c​r​a​f​t​-​c​m​s​-​3​-​w​e​b​s​i​t​e​-​w​i​t​h​-​a​-​c​u​s​t​o​m​-​m​odule](https://nystudio107.com/blog/enhancing-a-craft-cms-3-website-with-a-custom-module)
- [https://​verbb​.io/​b​l​o​g​/​e​v​e​r​y​t​h​i​n​g​-​y​o​u​-​n​e​e​d​-​t​o​-​k​n​o​w​-​a​b​o​u​t​-​m​o​dules](https://verbb.io/blog/everything-you-need-to-know-about-modules)
- [https://​johnhenry​.ie/​a​r​t​i​cles/…](https://johnhenry.ie/blog/2022/10/bending-the-craft-cms-control-panel)
- [https://​codepen​.io/​s​t​a​m​d​/​pen/B…](https://codepen.io/stamd/pen/BaJJrdq)

### Share this link via

###### Or copy link

Copy

[ Previous Blog Post

IA Presenter](https://johnhenry.ie/blog/2022/10/ia-presenter "Previous Blog Post")

[Next Blog Post

Surviving A Web Development Career](https://johnhenry.ie/blog/2022/10/surviving-a-web-development-career "Next Blog Post")

I'm a no-nonsense, experienced website developer who works with Content Management Sytems and specializes in Craft CMS.

[Lets Talk Today!](https://johnhenry.ie/contact)
