How can i add Unique value validation for custom field in created entry type for control panel in craft cms 3

116 Views Asked by At

I have created new field as field type entries..in that added one custom field named code.. so in the control panel, I have an entries type that can insert that code in the craft_content table.. now I want to add unique code value validation.. so how can I add a validation rule?

I have try with this event method

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']
          ];
        }
    );

And created one class file with name '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;
} 
0

There are 0 best solutions below