如何在 Craft cms 3 中为控制面板创建的条目类型中添加自定义字段的唯一值验证

问题描述 投票:0回答:0

我创建了新字段作为字段类型条目..其中添加了一个名为 code 的自定义字段..因此在控制面板中,我有一个条目类型可以在 craft_content 表中插入该代码..现在我想添加唯一的代码值验证..那么如何添加验证规则?

我尝试过这个事件方法

Event::on(
        Entry::class,
        Entry::EVENT_DEFINE_RULES,
        function(DefineRulesEvent $event) {
            /** @var Entry $entry */
            $entry = $event->sender;
            // Only worry about entries in the code section
            if ($entry->section->handle !== 'code') {
                return;
            }
          $event->rules[] = [
            ['code'],
            'unique',
            'targetClass' => CraftContentRecord::class,
            'message' => Craft::t('yii','{attribute} "{value}" has already been taken.'),
            'targetAttribute' => ['field_code']
          ];
        }
    );

并创建了一个名为“CraftContentRecord.php”的类文件

use craft\db\ActiveRecord;
use craft\db\Table;
class CraftContentRecord extends ActiveRecord
{
    public static function tableName()
    {
        return Table::CONTENT; // Use the actual table name in the database, which is usually prefixed with "{{%}}"
    }

    // Define the attributes that correspond to columns in the 'craft_content' table
    public $id;
    public $elementId;
    public $siteId;
    public $title;
} 
yii2 craftcms
© www.soinside.com 2019 - 2024. All rights reserved.