1

I'm building a plugin that has a column in the DB which is unique and essentially an AttributeType::Handle.

Here is the piece from the record:

return array(
    'key' => array(AttributeType::Handle, 'default' => '', 'required' => true),
);

And in my service after the $model has passed validation:

if ($record->save()) {
    // update id on model (for new records)
    $model->setAttribute('id', $record->getAttribute('id'));
    return true;
} else {
    $model->addErrors($record->getErrors());
    return false;
}

When does that handle validation happen? If I pass something that wouldn't pass handle validation (spaces or a reserved word), it doesn't save the record in the database, but it doesn't throw any errors.

In addition, is there a way to throw an error when the value isn't unique? Again, the record doesn't save if I use a key that is already in the DB, but there is no error.

Happy to provide more code if necessary, just didn't want to overcomplicate the question. Thanks!

  • Wow, just realized how dumb I was. I just needed to add the AttributeType::Handle to the model as well. But, I still have the question about throwing an error on uniqueness. – Trevor Davis Jan 7 '17 at 4:02
0

In addition, is there a way to throw an error when the value isn't unique? Again, the record doesn't save if I use a key that is already in the DB, but there is no error.

If you use 'unique' => true in an attribute on your record, Craft will use Yii's CUniqueValidator class to verify the uniqueness of an attribute in the database.

$record->validate() will fail and you can use $record->getErrors() to get the error message.

return array(
    'key' => array(AttributeType::Handle, 'default' => '', 'required' => true, 'unique' => true),
);
  • Ah, got it. $record->save() was always returning false, but I wasn't getting the errors from the record validation correctly. Got it working now, thanks! – Trevor Davis Jan 8 '17 at 15:11

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.