4

I have a custom field type which I need to be unique. So far I have this:

/**
 * Validates the field values is unique
 *
 * @param mixed $value
 *
 * @return true|string|array
 */
public function validate($value)
{
    $existingEntryCount = craft()->elements->getCriteria(ElementType::Entry)->total(array(
        $this->model->getAttribute('handle') => $value
    ));

    return ($existingEntryCount) ? $this->model->getAttribute('name') . Craft::t(' must be unique') : true;
}

This works in that it returns an error if any entry is found with the value submitted, however I need to restrict the search so that it excludes the current entry from the search query.

5

If anybody is interested, I created a simple unique text field plugin that extends the core text field: https://github.com/fuel-digital/Craft-Unique-Text-FieldType.

| improve this answer | |
  • 1
    So did I (github.com/joshangell/craft-unique-value) but yours looks to be much more bulletproof! – Josh Angell Nov 26 '14 at 15:58
  • I'm sure it could be improved - it's pretty bare bones but does the job. – Russ Back Nov 26 '14 at 16:02
  • Thanks Russ - this came up as a requirement in a new project... Thanks for contributing to the community! – Matt P Aug 8 '16 at 10:59
  • Thank you for this plugin. Is this also compatible with Craft v.3? – Panos Spiliotis Mar 1 '17 at 9:47
4

I came up with an answer, but be good to know if there is a better way of doing it:

/**
 * Checks if another entry exists with the given reference
 * 
 * @param  string $value The reference to check
 * @return bool
 */
private function referenceExists($value)
{
    $existing = craft()->elements->getCriteria(ElementType::Entry)->first(array(
        $this->model->getAttribute('handle') => $value
    ));

    return ($existing && $existing->getAttribute('id') != $this->element->getAttribute('id'));
}

/**
 * Validates the field values is unique
 *
 * @param mixed $value
 * @return true|string|array
 */
public function validate($value)
{
    return ($this->referenceExists($value)) ? $this->model->getAttribute('name') . Craft::t(' must be unique') : true;
}
| improve this answer | |
  • Am confused now as to whether that referenceExists() method should be in the plugin's service rather than the fieldtype too... – Russ Back Nov 25 '14 at 16:10

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.