2

I am learning to write my first plugin for Craft CMS 3.x

I have a field that gets displayed as a string, but is stored in the database as binary. When I validate it, I write:

public function getElementValidationRules(): array
{
    return [
        /* Other rules, */
        ['unique']
    ];
}

What I wonder is, will it get compared in its string form to the binary? Or will serializeValue() get called?

1 Answer 1

2

First of all: this validator requires an active record as target in order to know what table it should check to search for uniqueness. Since Craft has not such a thing you would need to create a record for the content table in order to make it work.

Furthermore you'll need to check the context of the field, if it's inside a matrix or inside a super table field or whatever so you need to set the target Attribute dynamically based on the table.

Finally it won't serialize your value automatically and search for the string, instead it will just fail because of these lines

foreach ($rawConditions as $key => $value) { 
    if (is_array($value)) { 
        $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.')); 
         return; 
    } 
    $conditions[] = [$key => $value];
}

Your value is an array so it will add an error no matter what

However: you can rebuild the functionality by actually validating the model by yourself with this validator instead of defining a validator and letting Craft handling it.

You can see an example in the matrix field it inserts just a function that is being called in the class instead of a validator. Then you can create a dynamic model and validate that one. You can read more about ad hock validations

$email = '[email protected]';
$validator = new yii\validators\EmailValidator(); 
if ($validator->validate($email, $error)) { 
    echo 'Email is valid.'; 
} else { 
    echo $error; 
}
2
  • Very informative comment, thank you very much. Could you suggest some resources on Records (Active Records since Craft 3?)? There isn't much in terms of documentation that I can find. Commented Oct 7, 2018 at 22:05
  • @DwarfVader Probably best to go to the Yii 2 docs for that: yiiframework.com/doc/guide/2.0/en/db-active-record
    – Brad Bell
    Commented Oct 10, 2018 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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