2

Is it possible to limit the title field in an entry? As with other fields I can adjust so that it only takes a certain amount of characters.

3

You can create a custom validation at the EVENT_BEFORE_SAVE event

Event::on(Entry::class,
    Entry::EVENT_BEFORE_SAVE,
    function(ModelEvent $event){
        /** @var Entry $entry */
        $entry = $event->sender;
        // you can check for the section and the type

        $model = DynamicModel::validateData(['title' => $entry->title], [
            [['title'], 'string', 'max' => 2, 'message'=>'{attribute} should not be longer than 2 characters']
        ]);
        if($model->hasErrors()){
            $entry->addErrors($model->getErrors());
            $event->isValid = false;
        }
});

You can leave remove the message attribute if you don't want to use a custom error message, I just wanted to provide a full example how to validate data in Yii2. That way you can define whatever rule you want

  • Thanks Robin, that is above my dev threshold level :) . I took a look in SavableComponent.php but not sure if that is where I make the change. – Vin Apr 27 '18 at 21:20
  • It's actually not that hard. If you are going to create a more complex site you'll need to create plugins. You should read the docs github.com/craftcms/docs/blob/v3/en/plugin-intro.md this change belongs into a module or plugin. There is not really another way to achieve it – Robin Schambach Apr 27 '18 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.